E167: 정밀도를 잃는 확장(widening) 상수 변환이에요

E167: 정밀도를 잃는 확장(widening) 상수 변환이에요 (Lossy Widening Constant Conversion)

숫자 리터럴이 정밀하게 표현할 수 없는 타입으로 자동 확장(widen)될 때 발생하는 경고예요. 보통 큰 정수 리터럴을 부동소수점 타입에 할당할 때 일어나요.

출처: Scala 3 Reference

본문

부동소수점 타입(FloatDouble)은 정밀도에 한계가 있어서 모든 정숫값을 정확하게 표현할 수는 없어요. 변환 과정에서 정밀도를 잃게 되면, 컴파일러가 .toFloat.toDouble을 사용해 변환을 명시적으로 만들라고 경고해 줘요.

Example

def example: Float = 16777217

Error

-- [E167] Lossy Conversion Warning: example.scala:1:21 -------------------------
1 |def example: Float = 16777217
  |                     ^^^^^^^^
  |                    Widening conversion from Int to Float loses precision.
  |                    Write `.toFloat` instead.

Solution

// Make the lossy conversion explicit
def example: Float = 16777217.toFloat
// Or use Double which has more precision
def example: Double = 16777217

더 알아보기

  • 숫자 리터럴과 타입 변환에 대한 자세한 내용은 Scala 3 Reference의 numeric literals 문서를 참고하세요.