December 2015
Intermediate to advanced
298 pages
5h 30m
English
Scala has singleton objects called companion objects. A companion object is an object with the same name as a class. A companion object also can access private methods and fields of its companion class. Both a class and its companion object must be defined in the same source file. The companion object is where the apply() factory method may be defined. Let's have a look at the following example of a companion class:
class Singleton { // Companion class
def m() {
println("class")
}
}And then its companion object as:
object Singleton { // Companion Object
def m() {
println("companion")
}
}It is that simple, when a case class is defined, Scala automatically generates a companion object for it.
If a companion ...
Read now
Unlock full access