gpt4 book ai didi

scala - 理解 Scala 中的类型推断

转载 作者:行者123 更新时间:2023-12-04 12:28:55 24 4
gpt4 key购买 nike

我编写了以下简单程序:

import java.util.{Set => JavaSet}
import java.util.Collections._

object Main extends App {
def test(set: JavaSet[String]) = ()

test(emptySet()) //fine
test(emptySet) //error
}

DEMO

最后一行 test(emptySet)真的很惊讶没有编译。为什么? test(emptySet())有什么区别?我认为在 Scala 中我们可以在这种情况下自由地省略括号。

最佳答案

Method Conversions在 Scala 规范中:

The following four implicit conversions can be applied to methods which are not applied to some argument list.

Evaluation

A parameterless method m of type => T is always converted to type T by evaluating the expression to which m is bound.

Implicit Application

If the method takes only implicit parameters, implicit arguments are passed following the rules here.

Eta Expansion

Otherwise, if the method is not a constructor, and the expected type pt is a function type (Ts′)⇒T′, eta-expansion is performed on the expression e.

Empty Application

Otherwise, if e has method type ()T, it is implicitly applied to the empty argument list, yielding e().



您想要的是“空应用程序”,但只有在没有早期转换的情况下才会应用它,在这种情况下,会发生“Eta 扩展”。

编辑:这是错误的,@Jasper-M 的评论是正确的。没有 eta 扩展发生,“空应用程序”目前不适用于泛型方法。

关于scala - 理解 Scala 中的类型推断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41237323/

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