虽然在某些情况下,这样的方法重载可能会导致歧义,但为什么编译器会禁止既不在编译时也不在运行时产生歧义的代码呢?
例子:
// 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");}
- user1609012