Back
Close

FP Module 2 - 101 Scala

Bubu
212 views

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
    }

}
max
min
factoriel
Create your playground on Tech.io
This playground was created on Tech.io, our hands-on, knowledge-sharing platform for developers.
Go to tech.io
codingame x discord
Join the CodinGame community on Discord to chat about puzzle contributions, challenges, streams, blog articles - all that good stuff!
JOIN US ON DISCORD
Online Participants