Scala 中的 eta 扩展是什么? [英] What is the eta expansion in Scala?

查看:80
本文介绍了Scala 中的 eta 扩展是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Scala 的新手.刚听过eta扩展"这个词,大致知道是将方法扩展为函数对象的意思.但是我在 SO 中发现很少有资源可以系统地介绍它.

我很好奇 eta 扩展在 Scala 中是如何工作的.需要eta扩展的场景有哪些?Scala 中如何实现eta 扩展?

我大致知道在这种情况下:

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

someMethod _ 大致会被翻译成一个新的函数对象,如下所示:

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

这就是 Scala 所做的一切吗?

解决方案

http://scala-lang.org/files/archive/spec/2.11/06-expressions.html#method-values.><块引用>

someMethod _ 大致会被翻译成一个新的函数对象,如下所示:

不完全是:实际上是

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

差异很重要,例如如果 someMethod 在某处被覆盖.

<块引用>

这就是 Scala 所做的一切吗?

您还需要考虑如果该方法采用多个参数列表(您得到一个返回函数的函数)或按名称参数会发生什么.

<块引用>

需要eta扩展的场景有哪些?

  1. 当您特别要求时(例如 someMethod _).

  2. 当您使用需要函数类型(或 Scala 2.12 中的 SAM 类型)值的方法(带参数)时.例如

    def foo(f: Int => Int) = ???foo(someMethod)

  3. 就是这样.

请注意,使用 eta-expansion 和带有占位符的匿名函数 (someMethod(_)) 可能会因类型推断、隐式等原因而表现不同.

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?

解决方案

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.

这篇关于Scala 中的 eta 扩展是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆