MOCKSTACKS
EN
Questions And Answers

More Tutorials









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


Conclusion

In this page (written and validated by ) you learned about Scala Classes and Objects . What's Next? If you are interested in completing Scala tutorial, your next topic will be learning about: Scala Collections.



Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue: mockstacks@gmail.com.


Share On:


Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using Mockstacks.com, you agree to have read and accepted our terms of use, cookies and privacy policy.