我正在阅读《Scala 编程》一书.在书中,它说一个函数文字被编译成一个类,当在运行时实例化时它是一个函数值".并且它提到函数值是对象,因此您可以根据需要将它们存储在变量中".
I am reading the book Programming in Scala. In the book, it says that "A function literal is compiled into a class that when instantiated at runtime is a function value". And it mentions that "Function values are objects, so you can store them in variables if you like".
所以我尝试检查函数之间的相等性.但我失败了.
So I try to check the equality between functions. But I failed.
如果函数是 Scala 中的对象,那么它的行为应该与 Scala 中的其他对象一样.也许检查函数的相等性是没有意义的,所以它被禁用了?
If function is object in Scala, then it should behave like other objects in Scala. Maybe check equality of function is meaningless, so it is disabled?
在Scala中函数会被编译成对象吗?
And will function be compiled into object in Scala?
推荐答案Lambda 被编译为匿名类(我记得不是 case 类).这意味着如果你这样做:
Lambda are compiled as anonymous classes (not case class, as far as I remember). That means if you do:
val f1: (String) => String = _ => "F1" val f2: (String) => String = _ => "F2"f1 和 f2 都是 Function1[String,String] 的子类型,但属于不同的匿名类,所以不能相等.
Both f1 and f2 are subtype of Function1[String,String], but they are of different anonymous classes, so can't equal.
如果你写成:
case class F(res: String) extends ((String) => String) { def apply(s: String) = res }那么:
val f1: (String) => String = F("A") val f2: (String) => String = F("A") f1 == f2 // true更多推荐
Scala 中的函数相等,是 Scala 中的函数对象吗?
发布评论