在Scala中定义主构造函数使用this关键字:
- 每一个辅助构造函数都需要调用之前定义的任何一个构造函数
- 每一个辅助构造函数都要有不同的参数表
- 一个构造函数使用this关键字调用另一个构造函数
scala> :paste
// Entering paste mode (ctrl-D to finish)
class Pizza(var crustSize: Int, var crustType: String) {
def this(crustSize: Int) {
this(crustSize, Pizza.DEFAULT_CRUST_TYPE)
}
def this(crustType: String) {
this(Pizza.DEFAULT_CRUST_SIZE, crustType)
}
def this() {
this(Pizza.DEFAULT_CRUST_SIZE, Pizza.DEFAULT_CRUST_TYPE)
}
override def toString = s"A $crustSize inch pizza with a $crustType crust"
}
object Pizza {
val DEFAULT_CRUST_SIZE = 12
val DEFAULT_CRUST_TYPE = "THIN"
}
// Exiting paste mode, now interpreting.
defined class Pizza
defined object Pizza
分别使用主构造函数和辅助构造函数来创建类的实例
//使用主构造函数
scala> val p1 = new Pizza(Pizza.DEFAULT_CRUST_SIZE, Pizza.DEFAULT_CRUST_TYPE)
p1: Pizza = A 12 inch pizza with a THIN crust
//使用辅助构造函数
scala> val p2 = new Pizza(Pizza.DEFAULT_CRUST_SIZE)
p2: Pizza = A 12 inch pizza with a THIN crust
scala> val p3 = new Pizza(Pizza.DEFAULT_CRUST_TYPE)
p3: Pizza = A 12 inch pizza with a THIN crust
scala> val p4 = new Pizza()
p4: Pizza = A 12 inch pizza with a THIN crust
要给case class定义一个辅助构造函数,需要在其伴生对象中增加apply方法。
scala> :paste
// Entering paste mode (ctrl-D to finish)
case class Person(var name: String, var age:Int)
object Person{
def apply() = new Person("<no name>", 0)
def apply(name: String) = new Person(name, 0)
}
// Exiting paste mode, now interpreting.
defined class Person
defined object Person
调用主构造函数和辅助构造函数来创建case class的实例对象
//辅助构造函数
scala> val a = Person()
a: Person = Person(<no name>,0)
//辅助构造函数
scala> val a = Person("Pam")
a: Person = Person(Pam,0)
//主构造函数
scala> val a = Person("William Shatner", 27)
a: Person = Person(William Shatner,27)
//修改姓名
scala> a.name = "Leonard Nimoy"
a.name: String = Leonard Nimoy
//修改年龄
scala> a.age = 78
a.age: Int = 78
//打印对象
scala> println(a)
Person(Leonard Nimoy,78)