例如,这是怎么回事:
class Cat(name: String, val age: Int) {
def this() = this("Garfield", 20)
}
val someCat = new Cat
someCat.age
res0: Int = 20
不同于:
class Cat(name: String = "Garfield", val age: Int = 20)
val someCat = new Cat
someCat.age
res0: Int = 20
Note: I have seen answers to other questions(e.g here) that discuss the differences between Java & Scala in the implementation for auxiliary constructors. But I am mostly trying to understand why do we need them in Scala, in the first place.
辅助构造函数不仅可以提供默认值,还可以带来更多好处。例如,以下示例可以接受不同类型的参数:
如果主构造函数包含实现详细信息,您还可以隐藏它:
This allows you to have
data
clearly be the backing structure for your class while avoiding cluttering your class with the arguments to one of your auxiliary constructors.辅助构造函数的另一个用途是将Java代码迁移到Scala,而不会破坏依赖关系。