Practical difference between def f(x: Int) = x+1 and val f = (x: Int) => x+1 in Scala

后端 未结 2 1719
清酒与你
清酒与你 2021-02-20 14:19

I\'m new to Scala and I\'m having a problem understanding this. Why are there two syntaxes for the same concept, and none of them more efficient or shorter at that (merely from

2条回答
  •  梦毁少年i
    2021-02-20 14:39

    As an extension to Ionut's first point, it may be worth taking a quick look at http://www.scala-lang.org/api/current/#scala.Function1.

    From my understanding, an instance of a function as you described (ie. val f = (x: Int) => x + 1) extends the Function1 class. The implications of this are that an instance of a function consumes more memory than defining a method. Methods are innate to the JVM, hence they can be determined at compile time. The obvious cost of a Function is its memory consumption, but with it come added benefits such as composition with other Function objects.

    If I understand correctly, the reason defs and lambdas can work together is because the Function class has a self-type (T1) ⇒ R which is implied by its apply() method https://github.com/scala/scala/blob/v2.11.8/src/library/scala/Function1.scala#L36. (At least I THINK that's what going on, please correct me if I'm wrong). This is all just my own speculation, however. There's certain to be some extra compiler magic taking place underneath to allow method and function interoperability.

提交回复
热议问题