Saturday 27 December 2008

Scala - object, singletons, classes and constructors

Today, a simple example by way of explanation of the basic constructs of OO in Scala.

Things to note:
  • Scala does not use static methods, in this sense Scala is more purely OO than Java.
  • The equivalent is achieved using object singletons and companion objects.

The following code example demonstrates:

  • Use of object singleton and "main" application entry point
  • Declaration of new objects
  • Declaration of new class
  • Class primary constructor
  • Declaring fields
  • Declaring alternative constructors
  • Use of override keyword

Example Code:

package test

// object declares a singleton (like Java static)
object Test {
// the usual main, takes an Array[String] of arguments
def main(args : Array[String]) {

var myClass1 = new MyClass(5, "Louis") // using primary constructor
var myClass2 = new MyClass(10); // using alternate constructor

// access public field value
println("myClass1.value1 = " + myClass1.value1)

// output using overriden toString
println("myClass1 = " + myClass1)
println("myClass2 = " + myClass2)
}
}

// define MyClass and its primary constructor (Int, String)
class MyClass(v1 : Int, s1 : String) {

// these are fields (public)
def value1 : Int = v1
def string1 : String = s1

// this is an alternate constructor (calls primary constructor)
def this(v1 : Int) = {
this(v1, "hello")
}

// can override toString like in Java, note no return statement required + the override keyword
override def toString() : String =
{
"MyClass: (" + value1 + ", " + string1 + ")"
}
}

No comments: