Why == operator and equals() behave differently for values of AnyVal in Scala

后端 未结 2 406
野趣味
野趣味 2020-12-09 04:37

In the scaladoc of scala.Any, the operator == (or, method ==) is explained:

The expression x == that

2条回答
  •  春和景丽
    2020-12-09 05:23

    I expect this was done because of auto-boxing and a desire to stay consistent with expectations held over from Java, and maths in generel (1 = 1.0 = 1 (represented as a long) etc.). For example, running comparisons between Scala numeric types and Java numeric types:

    scala> val foo: Long = 3L
    foo: Long = 3
    
    scala> val bar: Int = 3
    bar: Int = 3
    
    scala> foo == bar
    res0: Boolean = true
    
    scala> foo.equals(bar)
    res1: Boolean = false
    

    Compared with:

    scala> val jfoo = new java.lang.Long(3L)
    jfoo: Long = 3
    
    scala> val jbar = new java.lang.Integer(3)
    jbar: Integer = 3
    
    scala> jfoo == jbar
    res2: Boolean = true
    
    scala> jfoo.equals(jbar)
    res3: Boolean = false
    

提交回复
热议问题