Thursday, January 21, 2016

Learning Scala - Session 4 - First Class

First.scala class 

package com.first

class First {
  var name = ""
  var age = 0
  override def toString=s"name is $name, age is $age";  //override toString helps to directly print the obj

  object FirstObj {
    var obj = new First()
    obj.name = "Tanu"
    obj.age = 30
   
    def main(args:Array[String]){
      println(obj)   //directly print object if toString is overriden, if not, then prints reference
    }
  }
}

Output:
name is Tanu, age is 30

To run a scala program, we need to run the object and not the class

obj extends App

 object FirstObj extends App{
    var obj = new First()
    obj.name = "Tanu"
    obj.age = 30
      println(obj)
  }

extends App - by default puts all to main method, no need to define the main method. App is a Trait

Trait in scala is same as Interface with default implementation (more on this later)