Scala 中的函数相等,是 Scala 中的函数对象吗? [英] Equality of functions in Scala, is functions objects in Scala?

查看:39
本文介绍了Scala 中的函数相等,是 Scala 中的函数对象吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读《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.

  1. 如果函数是 Scala 中的对象,那么它的行为应该与 Scala 中的其他对象一样.也许检查函数的相等性是没有意义的,所以它被禁用了?

  1. 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"

f1f2 都是 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 中的函数对象吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆