E175: Value Discarding — 값 버리기

E175: Value Discarding — 값 버리기

Unit이 아닌 표현식의 값이 버려질 때(사용되지 않을 때) 발생하는 경고예요. 반환 값을 실수로 무시한 프로그래밍 실수를 자주 의미해요.

출처: Scala 3 Reference

본문

이 경고는 -Wvalue-discard 컴파일러 플래그로 켜져요. 에러 결과나 갱신된 컬렉션처럼 중요한 값을 처리하지 않는 버그를 잡는 데 도움돼요.

예시 (Example)

//> using options -Wvalue-discard

import scala.collection.mutable

def example: Unit = {
  mutable.Set.empty[String].remove("")
}

에러 (Error)

-- [E175] Potential Issue Warning: example.scala:6:34 --------------------------
6 |  mutable.Set.empty[String].remove("")
  |  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  |discarded non-Unit value of type Boolean. Add `: Unit` to discard silently.

해결 방법 (Solution)

//> using options -Wvalue-discard

import scala.collection.mutable

def example: Unit = {
  val set = mutable.Set.empty[String]
  // Use the return value
  val wasRemoved: Boolean = set.remove("")
  if wasRemoved then println("Removed")
}
//> using options -Wvalue-discard

import scala.collection.mutable

def example: Unit = {
  // Explicitly discard by adding : Unit
  mutable.Set.empty[String].remove(""): Unit
}

더 알아보기

반환 값을 쓰거나, 아니면 : Unit을 붙여 의도적으로 버린다는 걸 명시해주면 돼요.