constructors in scala (primary/auxiliary/default primary)

后端 未结 2 1817
一生所求
一生所求 2021-02-08 02:19

A quite simple exercise from Cay Horstmann\'s book « Scala for the impatient » keeps puzzling me. It\'s about primary,auxiliary and <

相关标签:
2条回答
  • 2021-02-08 03:02

    Actually, what I had in mind is a version with a no-argument primary constructor, like this:

    class Employee {
      private var _name = "John Q. Public"
      var salary = 0.0
      def this(n: String, s: Double) { this(); _name = n; salary = s; }
      def name = _name      
    }
    

    Clearly, this is inferior to defining the fields in the primary constructor, which is the point that I wanted to make.

    0 讨论(0)
  • 2021-02-08 03:08

    From "Programming in Scala, 2nd edition" paragraph 6.7:

    In Scala, every auxiliary constructor must invoke another constructor of the same class as its first action. The net effect of this rule is that every constructor invocation in Scala will end up eventually calling the primary constructor of the class. The primary constructor is thus the single point of entry of a class.

    So all data for initialization of val must be in primary constructor.

    Your class with explicit fields may be something like:

    class Employee(n: String = "John Q. Public", s: Double = 0.0) {
      val name = n
      var salary = s
    }
    

    or without default parameter values:

    class Employee(n: String, s: Double) {
      def this() = this("John Q. Public", 0.0)
      val name = n
      var salary = s
    }
    
    0 讨论(0)
提交回复
热议问题