FP Module 2 - 101 Scala

Bubu
7,371 views

Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content
Previous: Object / Singleton / Static Next: Trait

Companion: the best friend of a Class

A companion object is an object with the same name as a class or trait and defined in the same source file as the associated file or trait.

A companion object differs from other objects as it has access rights to the class/trait that other objects do not. In particular it can access methods and fields that are private in the class/trait.

// Pizza class
class Pizza (var crustType: String) {
    override def toString = "Crust type is " + crustType
}

// companion object
object Pizza {
    val CRUST_TYPE_THIN = "thin"
    val CRUST_TYPE_THICK = "thick"
    def getFoo = "Foo"
}

println(Pizza.CRUST_TYPE_THIN) // print "thin"
println(Pizza.getFoo) // print "Foo"

val p = new Pizza(Pizza.CRUST_TYPE_THICK)
println(p) // print "Crust type is thick"
User("John", "Doe") should return an instance of User named John Doe
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content