Friday, September 23, 2016

Extending a Class, Parametric Fields : Example...

scala> /****************************************
     |    An Abstract Class
     | *****************************************/
     | abstract class SubjectInfo {
     |   def name: String
     |   def mark: Int = 35
     |   def date: String = "2016/10/10"
     | }
defined class SubjectInfo

scala>

scala> /****************************************
     |    Extending the abstract class :
     |       This do not Compile
     | *****************************************/
     | class Math(mk: Int) extends SubjectInfo {
     |   // A method can also be overridden with a val #225
     |   // The reason we are able to do this is ; because
     |   //   in scala ; fields and methods share the same namespace
     |   // Scala has two namespaces
     |   //  values (fields, methods, packages & Singleton Objects)
     |   //  types (class & trait names)
     |   // Note here ; we are overriding an abstract method
     |   val name = "math"
     |
     |   // This gives compilation error ; any concrete method
     |   // overridden requires the 'override' modifier
     |   def mark = mk + 5
     | }
<console>:59: error: overriding method mark in class SubjectInfo of type => Int;
 method mark needs `override' modifier
         def mark = mk + 5
             ^

scala>

scala> /****************************************
     |    Extending the abstract class :
     |       This compiles successfully
     | *****************************************/
     | class Math(mk: Int) extends SubjectInfo {
     |   // A method can also be overridden with a val
     |   // Note here ; we are overriding an abstract method
     |
     |   val name = "math"
     |   // Using 'override' modifier...
     |   override val mark = mk
     |   override def date = "2016/10/15"
     | }
defined class Math

scala>

scala> /****************************************
     |     Parametric fields : Avoid unnecssary
     |           code smell
     | *****************************************/
     | class Math(
     |   // By prefixing 'val' / 'var' we specify the parameter
     |   //    and field has the same name
     |   // Other modifiers like ; private & protected are also possible
     |   //    #227
     |   override val mark: Int,
     |   val assignmentMark: Int
     | ) extends SubjectInfo {
     |   // A method can also be overridden with a val
     |   // Note here ; we are overriding an abstract method
     |
     |   val name = "math"
     | }
defined class Math