Scala Classes and Objects
Examples
Instantiate Class Instances
A class in Scala is a 'blueprint' of a class instance. An instance contains the state and behavior as defined by that class. To declare a class:
class MyClass{} // curly braces are optional here as class body is empty
An instance can be instantiated using new keyword:
var instance = new MyClass()
or:
var instance = new MyClass
Parentheses are optional in Scala for creating objects from a class that has a no-argumen constructor. If a class constructor takes arguments:
class MyClass(arg : Int) // Class definition
var instance = new MyClass(2) // Instance instantiation
instance.arg // not allowed
Here MyClass requires one Int argument, which can only be used internally to the class. arg cannot be accessed outside MyClass unless it is declared as a field:
class MyClass(arg : Int){
val prop = arg // Class field declaration
}
var obj = new MyClass(2)
obj.prop // legal statement
Alternatively it can be declared public in the constructor:
class MyClass(val arg : Int) // Class definition with arg declared public
var instance = new MyClass(2) // Instance instantiation
instance.arg //arg is now visible to clients
Instantiating class with no parameter: {} vs ()
Let's say we have a class MyClass with no constructor argument:
class MyClass
In Scala we can instantiate it using below syntax:
val obj = new MyClass()
Or we can simply write:
val obj = new MyClass
But, if not paid attention, in some cases optional parenthesis may produce some unexpected behavior. Suppose we want to create a task that should run in a separate thread. Below is the sample code:
val newThread = new Thread { new Runnable {
override def run(): Unit = {
// perform task
println("Performing task.")
}
}
}
newThread.start // prints no output