尽管在某些情况下,这种方法重载可能会变得模棱两可,但为什么编译器却不允许在编译时和运行时都模棱两可的代码呢?
例:
// 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方法后,很难找到默认参数。
object Test { def a[A](b: Int, c: Int, d: Int = 7): Unit = {}; def a[A](a:String, b: String = ""): Unit = {}; a(2,3,4); a("a");}