E129: Pure Expression In Statement Position — 문(statement) 위치의 순수 표현식 경고

E129: Pure Expression In Statement Position — 문(statement) 위치의 순수 표현식 경고

부수 효과가 없는 순수 표현식이 결과가 사용되지 않는 문 위치에 쓰일 때 컴파일러가 내는 경고예요.

출처: Scala 3 Reference

본문

부수 효과가 없는 순수 표현식이 결과가 사용되지 않는 문 위치에 쓰일 때 발생해요.

순수 표현식은 문 위치에서 아무 일도 하지 않아요. 부수 효과도 없고, 결과가 변수에 할당되거나 반환되지도 않으니까요. 이런 표현식은 프로그램의 의미를 바꾸지 않고 안전하게 제거할 수 있는데요, 보통은 할당이나 함수 호출이 빠진 프로그래밍 실수를 뜻하기도 해요.

예시

def example(): Unit =
  1
  ()

경고

-- [E129] Potential Issue Warning: example.scala:2:2 ---------------------------
2 |  1
  |  ^
  |  A pure expression does nothing in statement position
  |-----------------------------------------------------------------------------
  | Explanation (enabled by `-explain`)
  |- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  | The pure expression 1 doesn't have any side effect and its result is not assigned elsewhere.
  | It can be removed without changing the semantics of the program. This may indicate an error.
   -----------------------------------------------------------------------------

해결 방법

사용되지 않는 순수 표현식을 제거하면 돼요.

// Remove the unused pure expression
def example(): Unit =
  ()

값을 쓸 의도였다면 변수에 할당하면 되고요.

// Alternative: Assign the value to a variable if it was intended to be used
def example(): Int =
  val x = 1
  x + 1

표현식을 반환하려는 의도였다면, 뒤따르는 문을 제거하면 돼요.

// Alternative: If the expression was meant to be returned, remove trailing statements
def example(): Int =
  1