val 재할당

val 재할당 (Reassignment To Val)

val로 선언한 불변 변수에 값을 다시 넣으려 할 때 나오는 에러예요.

출처: Scala 3 Reference

본문

val로 선언한 불변 변수에 값을 다시 할당하려 하면 이 에러가 발생해요.

val은 초기화된 뒤에는 값을 바꿀 수 없으므로 새 값을 넣을 수 없어요. 재할당은 변수를 var로 선언했을 때만 가능해요.

만약 boolean 맥락에서 이 에러를 만났다면, ==(동등 비교)을 써야 할 자리에 =(할당)을 잘못 썼을 가능성이 커요.

예시

def example =
  val x = 1
  x = 2

에러 메시지

-- [E052] Type Error: example.scala:3:4 ----------------------------------------
3 |  x = 2
  |  ^^^^^
  |  Reassignment to val x
  |-----------------------------------------------------------------------------
  | Explanation (enabled by `-explain`)
  |- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  | You can not assign a new value to x as values can't be changed.
  | Reassigment is only permitted if the variable is declared with `var`.
   -----------------------------------------------------------------------------

해결 방법

// Use var if you need to reassign
def example =
  var x = 1
  x = 2
// Or use a new val with a different name
def example =
  val x = 1
  val y = 2
// If you meant to compare values, use ==
def example =
  val x = 1
  val isTwo = x == 2

더 알아보기

  • 값을 다시 넣어야 한다면 var를 쓰고, 아니면 이름이 다른 새 val을 만드는 게 깔끔해요.
  • 값을 비교하려는 의도였다면 ==를 사용하세요.