FP Module 2 - 101 Scala
Open Source Your Knowledge, Become a Contributor
Technology knowledge has to be shared and made accessible for free. Join the movement.
Object / Singleton / Static
An object is an instance of a Class. There are numerous cases where a developer would like to use one and only one instance of a Class (e.g: to define a cache, to use a DAO, utilities class, etc.).
Singleton in Java
In Java such kind of things is generaly achieved by the use of a pattern called "Singleton Pattern". Generaly, the class constructor is private and a static function called getInstance() is used to return the unique instance of the class.
** In Scala static keyword does not exist in Scala **
Object in Scala
In Scala, to have only one instance of a class you could directly use the keyword object instead of keyword Class.
object Welcome {
def french = "Bonjour le monde!"
def english = "Hello world!"
}
To use this object, you have to use his name:
class Main {
def main(args: Array[Sting] = { // main function as in Java
println(Welcome.french) // print "Bonjour le monde!"
println(Welcome.english) // print "Hello World!"
}
}
Functions are objects too, you can define a function as an object:
object Max {
def apply(x: Int, y: Int) = if (x < y) y else x
}
Max function, which is an object, can be used this way:
class Main {
def main(args: Array[Sting] = { // main function as in Java
println(Max(4,5)) // print 5
}
}