Reputation: 2030
I got this in the scala interpreter:
scala> val a:Float = 71F; val b:Int = 71; if (a==b) println ("?")
?
a: Float = 71.0
b: Int = 71
And I was wondering what are the exact semantics of this comparison. Even though I have a superficial knowledge of Scala I guess floating number arithmetic (and in this case I'm making sure of not using something equivalent to java's BigDecimal, or at least so I think) applies to this example. So "a" is not holding the number 71, as "b" is, but something close to it.
I think making any integer to floating point comparison yield false would have simplified things, but I am sure I must be missing something.
On a side note, I wonder if this could lead to any bugs in the code.
Upvotes: 1
Views: 230
Reputation: 8281
This comportment is inherited from Java due to an implicit conversion, as you can see in the Scaladoc
Implicit information
This member is added by an implicit conversion from Int to Integer performed by method int2Integer in scala.Predef.
For a safer equals, use ===
from Scalaz
Upvotes: 2
Reputation: 10764
Same thing happens in Java, as specified in JLS 15.21.1. Scala probably inherits this semantics for compatibility.
Upvotes: 5