Scala中辅助构造函数的用例是什么?

例如,这是怎么回事:

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.

评论
  • (艮)悲伤
    (艮)悲伤 回复

    辅助构造函数不仅可以提供默认值,还可以带来更多好处。例如,以下示例可以接受不同类型的参数:

    class MyBigInt(x: Int) {
      def this(s: String) = this(s.toInt)
    }
    

    如果主构造函数包含实现详细信息,您还可以隐藏它:

    class MyBigInt private(private val data: List[Byte]) {
      def this(s: String) = this(...)
      def this(n: Int) = this(...)
    }
    

    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,而不会破坏依赖关系。