Function equality in Scala, are functions of objects in Scala?

I am reading the book "Programming" in Scala. The book says that "A function literal is compiled into a class that, when instantiated at runtime, is the value of the function." And it mentions that "function values ​​are objects, so you can store them in variables if you want."

So I am trying to test for equality between functions. But I have failed.

  • If the function is an object in Scala, then it should behave like other objects in Scala. Perhaps the function equality check is pointless, that's why it's disabled?

  • And will the function be compiled into an object in Scala?

+3


source to share


2 answers


Lambda are compiled as anonymous classes (not a random class as far as I remember). This means that if:

val f1: (String) => String = _ => "F1"
val f2: (String) => String = _ => "F2"

      

Both f1

and f2

are subtypes Function1[String,String]

, but they have different anonymous classes, so they can not be equal.

If you write it like:



case class F(res: String) extends ((String) => String) {
  def apply(s: String) = res
}

      

Then:

val f1: (String) => String = F("A")
val f2: (String) => String = F("A")
f1 == f2 // true

      

+7


source


It is not clear what "equality" of functions means. Typically, people care about "Do these two functions perform the same result?"

It is, however, a well-known unsolvable problem, a function problem. The actual proof is more complicated, obviously, but a simple intuition is this: if you could tell if two functions were equal, then you could solve the halting problem by asking "is this function equal while (true) {}

?"



So, we cannot decide if two functions are evaluating the same result. For example, we can check if they contain the same code. But this is pretty boring. Just a little compiler optimization or renaming the same variable will make two functions intuitively supposed to be equal, not equal.

Ergo, we take a simple way out: two functions are equal if they are identical, otherwise they are not.

+4


source







All Articles