Search code examples
scalasetcompanion-object

Companion object for Set in Scala


From book 'Programming in Scala',doing this:

var jetSet = Set("Boeing", "Airbus")

invokes 'apply' on the companion object for scala.collection.immutable.Set, which returns an instance of a default, immutable Set.

But isn't companion object defined for the class with same name, and scala.collection.immutable.Set is a trait and not a class.So how come we have companion object for a trait?


Solution

  • Scala allows you to define a companion object for both traits and classes.

    Try it:

    trait Foo
    
    object Foo {
        def apply(x: Int): Foo = new Foo { }
    }
    

    Ih this example the companion object returns an instance of type Foo that is implemented as an anonymous class that extends the trait.