What is the eta expansion in Scala?

走远了吗. 提交于 2019-11-26 13:45:23

The definition, and some examples, are given in http://scala-lang.org/files/archive/spec/2.11/06-expressions.html#method-values.

someMethod _ will roughly be translated to a new function object like this:

Not quite: it's actually

new Function1[Int, Int] {
  def apply(x: Int): Int = someMethod(x)
}

The difference matters e.g. if someMethod is overridden somewhere.

Is it all that Scala does?

You also need to take into account what happens if the method takes multiple parameter lists (you get a function which returns a function) or by-name parameters.

What are the scenarios that eta expansion are needed?

  1. When you specifically ask for it (e.g. someMethod _).

  2. When you use a method (with parameters) where a value of a function type (or a SAM type in Scala 2.12) is expected. E.g.

    def foo(f: Int => Int) = ???
    
    foo(someMethod)
    
  3. That's it.

Note that using eta-expansion and an anonymous function with placeholders (someMethod(_)) can behave differently due to type inference, implicits, etc.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!