Scala错误:构造函数定义了两次

时间:2016-09-03 20:59:11

标签: 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 symbols both originated in file '.scala'
  def this(sub:Int){
      ^

2 个答案:

答案 0 :(得分:3)

你有两个必不可少的构造函数。

def this(name: Int) {
this(name, 5)
}

def this(sub:Int){
this(5, sub)
}

每个构造函数的签名应该不同,具有不同的变量名称不会使这两个构造函数不同。

答案 1 :(得分:2)

它没有编译,因为你有两个构造函数都将一个Int作为参数。

要了解问题的原因,请问自己如果做了new Name(2)会发生什么。它应该与new Name(2,5)还是new Name(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)