Tuesday, September 13, 2016

Class Syntax : Example 1

scala> class Subjects {
     |     //The default Access Modifier of a vairable is 'public' #101
     |     private var subjects:List[String] = Nil
     |
     |     //Always Specify Return type for Readability #103
     |     //Here we are using Cons operator to prepend (Constant time)
     |     //A method with Side effect is also called 'Procedure' #103
     |     def addSubject(subject: String):Unit = { subjects = subject :: subjects }
     |
     |     def getSubjects():List[String] = subjects
     | }
defined class Subjects

scala>

scala> val obj = new Subjects
obj: Subjects = Subjects@742dbac8

scala> obj.addSubject("Math")

scala> obj.addSubject("Science")

scala> obj.getSubjects()
res9: List[String] = List(Science, Math)
  • Curly Braces can be omitted for Class without Body #137
scala> class Subject(science: String, math: String)
defined class Subject

scala> val subject = new Subject("80", "90")
subject: Subject = Subject@20c0a64d