I explicitly specified a float type. This code produced an error. Why?
Currently, I am using scala v2.12.8
scala> val f: Float = 3.0
<console>:11: error: type mismatch;
found : Double(3.0)
required: Float
val f: Float = 3.0
I explicitly specified a float type. This code produced an error. Why?
Currently, I am using scala v2.12.8
scala> val f: Float = 3.0
<console>:11: error: type mismatch;
found : Double(3.0)
required: Float
val f: Float = 3.0
Use the following code:
val f: Float = 3f
If you don't add f suffix, the variable will be treated as double.
It's the same thing, that happens in java, since Double and Float wrap over java's double and float respectively:
jshell> float f = 3.0
| Error:
| incompatible types: possible lossy conversion from double to float
| float f = 3.0;
| ^-^
jshell> float f = 3.0f
f ==> 3.0
To have a Float you have to suffix it with a f:
scala> val f: Float = 3.0f
f: Float = 3.0
By default a floating number is a Double as the exception suggests.
From floating-point-literals (provided by Mario Galic):
Floating point literals are of type Float when followed by a floating point type suffix F or f, and are of type Double otherwise.
This behavior is fixed in Scala 3 (Dotty):
Starting dotty REPL...
Dotty compiler version 0.22.0-RC1 -- Copyright 2002-2020, LAMP/EPFL
scala> val x: Float = 3.14
val x: Float = 3.14
scala> Seq(3.14, 1)
val res0: Seq[Double] = List(3.14, 1.0)
scala> Seq[Float](3.14, 1)
val res1: Seq[Float] = List(3.14, 1.0)
It does not infer a type for a literal that would incur a lossy conversion:
scala> Seq(3.14f, 2147483646)
val res2: Seq[AnyVal] = List(3.14, 2147483646)
scala> Seq(3.14f, 2147483647)
val res3: Seq[Float] = List(3.14, 2147483647)
There is an open ticket to warn when a lossy conversion is required, but in general it works pretty well.