Thursday, September 15, 2016

Class Parameters, Primary Constructor, Precondition...

  • A Class can also take Class Parameters (ie...name, mark); using which a Primary Constructor with the same no of argument is created(by the Compiler)
  • Any code that is not a Field or a Method becomes part of Primary Constructor
scala> class Subject(var name: String, mark: Int) {
     |    //Specify Precondition for the Primary Constructor
     |    require(mark >= 0)
     |    // Override an existing Method
     |    override def toString() =
     |                   name + ", " + mark
     | }
defined class Subject

scala> val subject = new Subject("math", 80)
subject: Subject = math, 80

scala> //Class Parameters that are part of Primary Constructor is

scala> //not available to outside world

scala> println("name -> " + subject.name)
<console>:10: error: value name is not a member of Subject
              println("name -> " + subject.name)
                                           ^

scala> //Checking Precondition...

scala> val subject = new Subject("science", -1)
java.lang.IllegalArgumentException: requirement failed
 at scala.Predef$.require(Predef.scala:221)
 at Subject.<init>(<console>:9)