DPM
DPM

Reputation: 2030

Why in scala a comparison between integer and floating point such as 71 == 71.0 is true?

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

Answers (2)

Yann Moisan
Yann Moisan

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

ghik
ghik

Reputation: 10764

Same thing happens in Java, as specified in JLS 15.21.1. Scala probably inherits this semantics for compatibility.

Upvotes: 5

Related Questions