Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
201 views
in Technique[技术] by (71.8m points)

What is the eta expansion in Scala?

I am new to Scala. I just heard the term "eta expansion" and roughly know that it means to expand a method to a function object. But I find few resources in SO that systematically introduce it.

I am curious about how eta expansion works in Scala. What are the scenarios that eta expansion are needed? And how eta expansion is implemented in Scala?

I roughly know that in cases like this:

def someMethod(x: Int): Int = x * x

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

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

Is it all that Scala does?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...