1

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.

DPM
  • 1,960
  • 3
  • 26
  • 49

2 Answers2

5

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

ghik
  • 10,706
  • 1
  • 37
  • 50
  • I knew about Java, but I couldn't find how it works for Scala. (I also would expect Scala to work in a different way and make a more clever use of its complex type system) – DPM Nov 09 '13 at 15:50
  • @Jubbat Sure it may be a burden, but changing such fundamental things like numerical operator semantics would probably be very harmful as the Java semantics is now ubiquitous. – ghik Nov 09 '13 at 16:00
2

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

Yann Moisan
  • 8,161
  • 8
  • 47
  • 91