Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/powerbi/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Scala错误:构造函数定义了两次_Scala_Constructor - Fatal编程技术网

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)