snu-sf-class / pp202302

Programming Principles, SNU 4190.210, 2023 Fall
22 stars 7 forks source link

프로젝트 3번 IOType 질문 #76

Open koojahyeok opened 8 months ago

koojahyeok commented 8 months ago
enum IOType:
  case StdIO
  case DummyIO(var input: String, var output: String)

IOType 정의가 이렇게 되어있는데

given Reader[IOType] with
  extension (r: IOType)
    // Hint: Use scala.Console.in.read().toChar
    def readChar(): Option[Char] = r match {
      case StdIO => Some(scala.Console.in.read().toChar)
      case DummyIO(input, output) => {
        val char = input.headOption
        input = input.drop(1)
        char
      }
      case _ => None
    }

reader에서 DummyIO input에 접근하여 input을 수정하려 하니 val으로 선언되어 있어 안된다고 합니다. IOType 정의상에는 var로 되어있는데 제가 잘못 짚고 있는것일까요?

MerHS commented 8 months ago

case로 나눠서 받을때는 위와 같이 case를 쓰면 input이랑 output 자체는 case 블록 내에 정의된 새로운 val 값으로써 받아들이게 됩니다.

case DummyIO 내부의 값을 변경하기 위해서는

case v@DummyIO(_, _) =>
  v.output += "some value"

와 같이 값 전체를 v라는 변수에 할당한 후에 v 내부의 값을 변경하거나, r을 직접 변경하시면 됩니다.

koojahyeok commented 8 months ago

넵 감사합니다!