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
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
In this article