Scala 中的函数相等,是 Scala 中的函数对象吗?

编程入门 行业动态 更新时间:2024-10-10 23:23:15
本文介绍了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.

  • 如果函数是 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 中的函数对象吗?

    本文发布于:2023-11-25 23:23:44,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1631762.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:函数   对象   Scala

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!