Type mismatch error when assigning literal to Float

Ivan Lee :

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
som-snytt :

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.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=415531&siteId=1