gpt4 book ai didi

scala - 为什么 Scala 编译器不允许使用默认参数的重载方法?

转载 作者:行者123 更新时间:2023-12-05 01:03:10 24 4
gpt4 key购买 nike

虽然可能存在这样的方法重载可能变得模棱两可的有效情况,但为什么编译器不允许在编译时和运行时既不模棱两可的代码呢?

示例:

// This fails:
def foo(a: String)(b: Int = 42) = a + b
def foo(a: Int) (b: Int = 42) = a + b

// This fails, too. Even if there is no position in the argument list,
// where the types are the same.
def foo(a: Int) (b: Int = 42) = a + b
def foo(a: String)(b: String = "Foo") = a + b

// This is OK:
def foo(a: String)(b: Int) = a + b
def foo(a: Int) (b: Int = 42) = a + b

// Even this is OK.
def foo(a: Int)(b: Int) = a + b
def foo(a: Int)(b: String = "Foo") = a + b

val bar = foo(42)_ // This complains obviously ...

有什么理由不能放宽这些限制吗?

特别是当将重载的 Java 代码转换为 Scala 默认参数非常重要时,在用一个 Scala 方法替换大量 Java 方法后发现规范/编译器强加了任意限制并不好。

最佳答案

我想引用 Lukas Rytz(来自 here):

The reason is that we wanted a deterministic naming-scheme for the generated methods which return default arguments. If you write

def f(a: Int = 1)

the compiler generates

def f$default$1 = 1

If you have two overloads with defaults on the same parameter position, we would need a different naming scheme. But we want to keep the generated byte-code stable over multiple compiler runs.



future Scala 版本的解决方案可能是将非默认参数的类型名称(位于方法开头的那些,消除重载版本的歧义)合并到命名模式中,例如在这种情况下:
def foo(a: String)(b: Int = 42) = a + b
def foo(a: Int) (b: Int = 42) = a + b

它会是这样的:
def foo$String$default$2 = 42
def foo$Int$default$2 = 42

有人愿意 write a SIP proposal ?

关于scala - 为什么 Scala 编译器不允许使用默认参数的重载方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4652095/

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