Scala中是否存在功能平等的概念?
scala> def foo(x: Int) = x + 1 foo: (x: Int)Int scala> def bar(x: Int) = x + 1 bar: (x: Int)Int
所以我不能打电话==
给一个功能.
scala> foo == bar:10: error: missing arguments for method foo; follow this method with `_' if you want to treat it as a partially applied function foo == bar ^
除了验证所有x的foo(x)
== (不知道如何做到这一点),我还能如何验证相等性?bar(x)
你不会真的期望==
产生除false以外的任何东西,因为==
意味着"具有相同的内存地址",除非它是专门为该类定义的.毕竟,
scala> class A scala> (new A) == (new A) res0: Boolean = false
如果Function1
确实尝试提供实现==
,则不清楚它将检查什么.所有可能的投入都有相同的结果 同样的行为?相同的字节码?
如果你想要一个具有良好定义的相等操作的函数类,你必须自己编写它:
class Adder(private val toAdd: Int) extends (Int => Int) { override def apply(n: Int) = n + toAdd override def equals(other: Any) = other match { case o: Adder => this.toAdd == o.toAdd case _ => false } }
然后你可以这样做:
scala> val foo = new Adder(1) foo: Adder = <function1> scala> val bar = new Adder(1) bar: Adder = <function1> scala> foo(2) res4: Int = 3 scala> foo == bar res5: Boolean = true
要获得更简单的解决方案,只需将您的类设为a case class
,即可免费获得equals
和hashCode
实现:
case class Adder(private val toAdd: Int) extends (Int => Int) { override def apply(n: Int) = n + toAdd }