检查var在Scala中是哪个匿名函数

Check which anonymous function a var is in Scala

我有一个场景,我将匿名函数存储在 var

val x = Integer.max _

我想做一些像

这样的逻辑
if(x == Integer.max _){
    println("Using the max function")
}

但我注意到这些匿名函数永远不会彼此相等。

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

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

所以无论如何我可以检查我有什么匿名函数;如果我做不到,模仿此功能的最佳方式是什么?

A​​FAICT 没有干净的方法可以做到这一点。问题是 Scala 将所有匿名函数编译成匿名函数 类 - 所以不同的匿名函数得到不同的 类 (因此 == 表明它们是不同的)。

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

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

简单的解决方案是为您将使用的匿名函数创建一个变量。例如,

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

否则,您可以尝试验证两个函数的匿名 类 在结构上是否相同,但结果可能会非常令人不快。