Scala:在扩展参数化 Class 时处理不同的构造函数

Scala: handle different constructor when extending a parameterised Class

我正在编写 scala 代码,并希望在扩展参数化时处理不同的构造函数 Class。例如:

class Person (val name:String, val age: Int)
class Employee(name:String, age:Int, val position:String) 
      extends Person(name, age)

但是,我想要的是Employee可以有两个构造函数,一个是拿Person的信息来构造,一个是拿另一个Employee来构造:

val emply1 = new Employee(yzh, 30, CEO)
val emply2 = new Employee(emply1)

如果我想让两个构造函数都工作,我该怎么做?

谢谢!

如果你想要两个构造函数,你只需写两个构造函数:

class Person(val name: String, val age: Int)
class Employee(name: String, age: Int, val position: String) extends 
  Person(name, age) {
  def this(e: Employee) = this(e.name, e.age, e.position)
}

val emply1 = new Employee("yzh", 30, "CEO")
val emply2 = new Employee(emply1)

您需要添加一个腋下构造器。

class Employee(name:String, age:Int, val position:String)
  extends Person(name, age) {
  def this(emp: Employee) = this(emp.name, emp.age, emp.position)
}

如果你的 Employeecase class 那么你可以这样做。

val emply1 = Employee("yzh", 30, "CEO")
val emply2 = emply1.copy()