Equality of functions in Scala, is functions objects in Scala?

后端 未结 2 799
情书的邮戳
情书的邮戳 2020-12-19 13:32

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

2条回答
  •  难免孤独
    2020-12-19 13:53

    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"
    

    Both f1 and f2 are subtype of Function1[String,String], but they are of different anonymous classes, so can't equal.

    If you write it as:

    case class F(res: String) extends ((String) => String) {
      def apply(s: String) = res
    }
    

    Then:

    val f1: (String) => String = F("A")
    val f2: (String) => String = F("A")
    f1 == f2 // true
    

提交回复
热议问题