虽然可能存在这样的方法过载可能变得模糊的有效情况,但为什么编译器不允许在编译时和运行时都不模糊的代码?
例:
// 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 …Run Code Online (Sandbox Code Playgroud) 我已经定义了多个构造函数,在所有构造函数中都有一些默认参数值.看起来正确(我看不出任何歧义),但Scala(2.8)编译器抱怨:
多个重载的构造函数替代定义默认参数
这是否意味着我根本无法为重载的构造函数定义默认值?
让我来说明一下情况(当然是原始的,但是说明性的):
class A(subject : Double, factor : Int = 1, doItRight : Boolean = true) {
def this (subject : Int, factor : Int = 1, doItRight : Boolean = true) = {
this(subject.toDouble , factor, doItRight)
}
def this (subject : String, factor : Int = 1, doItRight : Boolean = true) = {
this(subject.toDouble , factor, doItRight)
}
def this () = {
this(defaultSubject)
}
}