Scala Language Instantiate Class Instances


Example

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-argument 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