scala> //#PS:72
scala> //psn > a30 > a30
scala> class MyClass(val myStr:String) {
| // Example : A method that has an empty argument List
| // **Round brackets are NOT used
| def firstPrint = println(myStr)
| // Example : A method that has an empty argument List
| // **Round brackets are used
| def secondPrint():Unit = println(myStr)
| }
defined class MyClass
scala>
scala> val obj = new MyClass("This is a demo")
obj: MyClass = MyClass@2b6dbbd1
scala> // Round brackets is not used
scala> obj.firstPrint
This is a demo
scala> // This do not work as we have defined this method
scala> // with no round brackets
scala> obj.firstPrint()
<console>:10: error: Unit does not take parameters
obj.firstPrint()
^
scala> // Round brackets is NOT used
scala> obj.secondPrint
This is a demo
scala> // Round brackets is used
scala> obj.secondPrint()
This is a demo
Best Practice
It has been a convention to define an Empty argument List method without Brackets, when that method has no side effect(Example "mydata".size)
No comments:
Post a Comment