Thursday, September 22, 2016

Parameterless methods & empty-paren methods : Example...

A Parameterless method should be called without parenthesis
scala> class SubjectInfo(nm: String, mk: Int){
     |     //A parameterless method #220
     |     //  Use this convention when a method simply
     |     //  provides access to a property
     |     def name = nm
     |     def mark = mk
     |
     |     //An empty-parent method
     |     //  Use this convention when the method
     |     //  does some operation or have side effects
     |     def printInfo() = {
     |         println("subject -> " + name +
     |                     ", mark -> " + mark)
     |     }
     | }
defined class SubjectInfo

scala>

scala> val sInfo = new SubjectInfo("math", 50)
sInfo: SubjectInfo = SubjectInfo@2267b0bb

scala>
     | /************************************
     |     Calling a Parameterless method
     | *************************************/
     | //This convention of using Parameterless method
     | //supports 'uniform access principle' #221
     | val name = sInfo.name
name: String = math

scala>

scala> //Calling a Parameterless method with

scala> //Parenthesis gives Compilation error

scala> val name = sInfo.name()
<console>:30: error: not enough arguments for method apply: (index: Int)Char in class StringOps.
Unspecified value parameter index.
       val name = sInfo.name()
                            ^

scala>

scala> /************************************
     |     Calling an empty-paren method
     | *************************************/
     | //An empty-parent method can be called without
     | //  parenthesis
     | //It is always recommended/best practice
     | //  to call empty paren method with parenthesis
     | //  or else it will look like a property
     | sInfo.printInfo
subject -> math, mark -> 50

scala>

scala> //Always call an empty-parent method using

scala> //empty parenthesis

scala> sInfo.printInfo()
subject -> math, mark -> 50