gpt4 book ai didi

Scala IDE 警告 : "anonymous function convertible to method value"

转载 作者:行者123 更新时间:2023-12-04 10:49:34 31 4
gpt4 key购买 nike

假设我想为一个方法创建一个别名:

def foo = bar(_)

这将警告说

Anonymous function convertible to a method value



我不太确定那是什么意思,因为当我尝试我认为这可能意味着:
def foo = bar

我收到一个错误

Missing arguments for method bar(a:A)

Cannot resolve reference bar with such signature.

最佳答案

首先,如果你想为方法创建一个“别名”,这就足够了:

scala> val foo = bar(_) //val instead of def, still warning from Idea
foo: Int => Int = <function1>

其次,这应该删除 Idea 的警告:
scala> val foo = bar _
foo: Int => Int

实际上,这不仅仅是别名 - 您的方法被转换为 function (eta扩展)。您不能只指定方法(编译时实体),因为编译器会期望参数 - 您需要先将其转换为函数(使用下划线)。有时当编译器需要一个函数时它会自动完成:
scala> val foo: Int => Int = bar
foo: Int => Int = <function1>

所以这可能是 Idea 想要从你那里得到的。在其他情况下 - 您必须明确使用 eta 扩展运算符( _ )。

P.S/1。 def foo = bar(_) ( def 而不是 val )没有意义,因为它每次都会返回新的(但相同的)函数, val (或 lazy val 为了安全起见 NullPointerException )只返回一次。

P.S/2。 difference between (_)_是第一个是部分应用函数(它会自动执行 _ eta-expansion),这意味着让我们说:
scala> def bar(a: Int, b: Int) = a
bar: (a: Int, b: Int)Int

scala> def foo = bar _
foo: (Int, Int) => Int

scala> def foo = bar(_)
<console>:8: error: missing parameter type for expanded function ((x$1) => bar(x$1))
def foo = bar(_)
^
<console>:8: error: not enough arguments for method bar: (a: Int, b: Int)Int.
Unspecified value parameter b.
def foo = bar(_)
^

scala> def foo = bar(_, _)
foo: (Int, Int) => Int

您必须指定 bar(_, _)因为有两个论点。

关于Scala IDE 警告 : "anonymous function convertible to method value",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31229833/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com