Scala错误:构造函数定义了两次
为什么不编译Scala错误:构造函数定义了两次,scala,constructor,Scala,Constructor,为什么不编译 class Name(val name: Int, val sub: Int) { def this() { this(5, 5) } def this(name: Int) { this(name, 5) } def this(sub:Int){ this(5, sub) } } 错误: .scala:15: error: constructor Name is defined twice conflicting sym
class Name(val name: Int, val sub: Int) {
def this() {
this(5, 5)
}
def this(name: Int) {
this(name, 5)
}
def this(sub:Int){
this(5, sub)
}
}
错误:
.scala:15: error: constructor Name is defined twice
conflicting symbols both originated in file '.scala'
def this(sub:Int){
^
您有两个基本相同的构造函数
def this(name: Int) {
this(name, 5)
}
def this(sub:Int){
this(5, sub)
}
每个构造函数的签名应该不同,具有不同的变量名不会使这两个构造函数不同。它不会编译,因为您有两个构造函数,它们都以单个
Int
作为参数
要理解这是一个问题的原因,请扪心自问,如果您使用了新名称(2)
,会发生什么。它应该与新名称(2,5)
或新名称(5,2)
相同吗?编译器怎么知道你想要哪一个呢
以下是如何使用Scala的默认参数功能来完成所需操作的建议:
class Name(val name: Int = 5, val sub: Int = 5)
new Name()
new Name(2, 2)
new Name(name=2)
new Name(sub=2)