What's the difference between == and .equals in Scala?

前端 未结 5 1763
小鲜肉
小鲜肉 2020-11-28 02:28

What is the difference between == and .equals() in Scala, and when to use which?

Is the implementation same as in Java?

EDIT: The r

5条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-28 02:55

    There is an interesting difference between == and equals for Float and Double types: They treat NaN differently:

    scala> Double.NaN == Double.NaN
    res3: Boolean = false
    
    scala> Double.NaN equals Double.NaN
    res4: Boolean = true
    

    Edit: As was pointed out in a comment - "this also happens in Java" - depends on what exactly this is:

    public static void main(final String... args) {
        final double unboxedNaN = Double.NaN;
        final Double boxedNaN = Double.valueOf(Double.NaN);
    
        System.out.println(unboxedNaN == unboxedNaN);
        System.out.println(boxedNaN == boxedNaN);
        System.out.println(boxedNaN.equals(boxedNaN));
    }
    

    This will print

    false
    true
    true
    

    So, the unboxedNan yields false when compared for equality because this is how IEEE floating point numbers define it and this should really happen in every programming language (although it somehow messes with the notion of identity).

    The boxed NaN yields true for the comparison using == in Java as we are comparing object references.

    I do not have an explanation for the equals case, IMHO it really should behave the same as == on unboxed double values, but it does not.

    Translated to Scala the matter is a little more complicated as Scala has unified primitive and object types into Any and translates into the primitive double and the boxed Double as needed. Thus the scala == apparently boils down to a comparison of primitive NaN values but equals uses the one defined on boxed Double values (there is a lot of implicit conversion magic going on and there is stuff pimped onto doubles by RichDouble).

    If you really need to find out if something is actually NaN use isNaN:

    • Java: https://docs.oracle.com/javase/7/docs/api/java/lang/Double.html#isNaN(double)
    • Scala: http://www.scala-lang.org/files/archive/api/2.11.8/index.html#scala.Double@isNaN():Boolean

提交回复
热议问题