Skip to content

Assigning integral literals to floating-point types should warn when losing precision #11333

@kynthus

Description

@kynthus

Compiler version

3.0.0-M3

Minimized example

val f1: Float  = 123456789            // Loses precision without saying anything. (Int => Float)
val d1: Double = 1234567890123456789L // Same as above. (Long => Double or Long => Float)

val  n: Int    = 123
val  l: Long   = 123456L

val f2: Float  = n // Assignment from variable is warning. (Int => Float)
val d2: Double = l // Same as above. (Long => Double or Long => Float)

Output

No warning when assigning integral literals.
However, I always get a warning when assigning from variables such as Int and Long.

Starting scala3 REPL...
Scala compiler version 3.0.0-M3 -- Copyright 2002-2020, LAMP/EPFL
scala> val f1: Float  = 123456789            // Loses precision without saying anything. (Int => Float)
val f1: Float = 1.23456792E8

scala> val d1: Double = 1234567890123456789L // Same as above. (Long => Double or Long => Float)
val d1: Double = 1.23456789012345677E18

scala> val  n: Int    = 123
     | val  l: Long   = 123456L
val n: Int = 123
val l: Long = 123456

scala> val f2: Float  = n // Assignment from variable is warning. (Int => Float)
1 |val f2: Float  = n
  |                 ^
  |method int2float in object Int is deprecated since 2.13.1: Implicit conversion from Int to Float is dangerous because it loses precision. Write `.toFloat` instead.
val f2: Float = 123.0

scala> val d2: Double = l // Same as above. (Long => Double or Long => Float)
1 |val d2: Double = l
  |                 ^
  |method long2double in object Long is deprecated since 2.13.1: Implicit conversion from Long to Double is dangerous because it loses precision. Write `.toDouble` instead.
val d2: Double = 123456.0

Expectation

I expected to be warned even with integral literal assignments.

It seems that there was a hot discussion about widening conversion of value types.

On the other hand, it is strange that the warning does not occur only in the case of literals.
Using Scala 2.13.2 to 2.13.4, Doing the same will give you a warning.

Welcome to Scala 2.13.2 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_202).
Type in expressions for evaluation. Or try :help.

scala> val f1: Float  = 123456789
                        ^
       warning: Widening conversion from Int to Float is deprecated because it loses precision. Write `.toFloat` instead.
val f1: Float = 1.23456792E8

scala> val d1: Double = 1234567890123456789L
                        ^
       warning: Widening conversion from Long to Double is deprecated because it loses precision. Write `.toDouble` instead.
val d1: Double = 1.23456789012345677E18

I understand that unlike Scala 2, Scala 3 doesn't have the concept of widening conversion.
Isn't checking integral literals realistic?

Metadata

Metadata

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions