Scala constructor overload?

前端 未结 5 1442
栀梦
栀梦 2020-11-27 15:27

How do you provide overloaded constructors in Scala?

5条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-27 15:41

    It's worth explicitly mentioning that Auxiliary Constructors in Scala must either call the primary constructor (as in landon9720's) answer, or another auxiliary constructor from the same class, as their first action. They cannot simply call the superclass's constructor explicitly or implicitly as they can in Java. This ensures that the primary constructor is the sole point of entry to the class.

    class Foo(x: Int, y: Int, z: String) {  
      // default y parameter to 0  
      def this(x: Int, z: String) = this(x, 0, z)   
      // default x & y parameters to 0
      // calls previous auxiliary constructor which calls the primary constructor  
      def this(z: String) = this(0, z);   
    }
    

提交回复
热议问题