Scala Objects - chrisbitm/python GitHub Wiki

An Object acts as a single instance. An Object is an instance of a Class.

Objects

object Greet {
   def toGreet(): String = {
      return ("Hello")
   }
}
def main(args: Array[String]): Unit = {
   var greeting = Greet.toGreet()
   print(greeting)

}
  • object Greet defines the Object's Name. It acts as a single instance of a class. The Main Method along with any Functions to pass will go in here. The name must start with a Capital Letter.
  • def toGreet is a function that has a String Return Type and returns greeting.
  • var greeting is given the String Good Morning.
  • toGreet(greeting) is the Function call assigned to g1.
  • println(g1) will output Good Morning.

Below is the same thing but within a class.

class Intro(var greeting: String) {
    def toGreet(): String = {
        return greeting;
    }
}
object Greet {
    def main(args: Array[String]): Unit = {
        var greeting = "Good Morning"
        var g1 = new Intro(greeting)
        println( g1.toGreet() )
    }
}
Good Morning
  • class Intro defines the Class name. The name can be whatever you want, but it has to start with a Capital Letter.
  • var greeting: String is the initialization parameter whenever a new Object is created. You have to declare either var or val when defining initialization parameters.
  • def toGreet is a function that has a String Return Type and returns greeting.
  • object greet is a single instance of a class. The Main Method along with any Functions to pass will go in here.