Back
Close

FP Module 2 - 101 Scala

Bubu
213 views
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
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