문제

This helpful StackOverflow answer states that it's not possible to compare two functions.

For the following, I get `false, as expected:

def

scala> def add1Test: Int => Int = { println("3"); _ + 1 }
add1Test: Int => Int

scala> add1Test == add1Test
3
3
res4: Boolean = false

scala> :t add1Test(5)
Int

Function1

scala> def foo: Function1[Int, Int] = _ + 1
foo: Int => Int

scala> :type foo
Int => Int

scala> foo == foo
res6: Boolean = false

val

However, for a val, I get true.

scala> val valAdd1: Int => Int = { println("val"); _ + 1}
val
valAdd1: Int => Int = <function1>

scala> valAdd1 == valAdd1
res3: Boolean = true

scala> :t valAdd1
Int => Int

Why does comparing def and Function result in false, but true for a val?

Also, why is false, rather than other behavior (ex: Exception thrown), returned when comparing a def and Function?

도움이 되었습니까?

해결책

The first two cases yield false because add1Test == and1Test (as well as foo == foo) compares two different objects which implement Function1 interface. add1Test == and1Test translates to something like new AbstractFunction1() { ... }.equals(new AbstractFunction1() { ... }) (due to the specialization of primitives the actual code is a bit more complicated but the idea is the same). Since the left side and the right side refer to different objects and the equivalence of functions is just equivalence of their instances, the result is false.

The third case compares the same object (because it was created via val) and therefore returns true.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top