2

I have a scenario where I have an anonymous function stored in a var

val x = Integer.max _

and I want to do some logic like

if(x == Integer.max _){
    println("Using the max function")
}

But I've noticed that these anonymous functions never equal each other.

val x = Integer.max _
val y = Integer.max _

println(x==y)   //false 
println(x eq y) //false

So is there anyway I can check what anonymous function I have; and if I can't what's the best way to mimic this functionality?

Ryan Stull
  • 1,056
  • 14
  • 35

1 Answers1

2

AFAICT there is no clean way of doing this. The problem is that Scala compiles all anonymous functions into anonymous classes - so different anonymous functions get different classes (hence why == indicates they are different).

scala> val x: (Int, Int) => Int = Integer.max
x: (Int, Int) => Int = <function2>

scala> x.getClass
res: Class[_ <: (Int, Int) => Int] = class $anonfun$1

The simple solution is to make a variable for the anonymous function you will use. For example,

val max: (Int, Int) => Int = Integer.max
...
val x = max
...
if (x == max) {
    println("Using the max function")
}

Otherwise, you might try verifying that the anonymous classes for both functions are structurally identical, but that might turn out to be pretty unpleasant.

Alec
  • 31,829
  • 7
  • 67
  • 114
  • Thank you, this will work for my purposes. Though it would be nice if scala compiled the same function into the same class each time. – Ryan Stull Jul 29 '16 at 22:11