Back to Scala3

E167: Lossy Widening Constant Conversion

docs/_docs/reference/error-codes/E167.md

3.8.41.4 KB
Original Source

E167: Lossy Widening Constant Conversion

This warning occurs when a numeric literal is automatically widened to a type that cannot represent it precisely. This typically happens when assigning large integer literals to floating-point types.

Floating-point types (Float and Double) have limited precision and cannot exactly represent all integer values. When a conversion would lose precision, the compiler warns you to make the conversion explicit using .toFloat or .toDouble.


Example

scala
def example: Float = 16777217

Error

scala
-- [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

scala
// Make the lossy conversion explicit
def example: Float = 16777217.toFloat
scala
// Or use Double which has more precision
def example: Double = 16777217
<!-- SOURCE-ONLY: Remove the notice below once this page has been manually updated. --> <aside class="warning"> This reference page was created with LLM assistance - the description of the error code may not be accurate or cover all possible scenarios. </aside>