scalakotlincompanion-objectkotlin-companion

Companion objects benefits of posibility to implement interfaces


Why in Kotlin/Scala companion objects can implements some interfaces, what benefits this can have? When is useful to use this feature?


Solution

  • Because companion objects are objects, objects can implement interfaces (or extend classes), and there is no good reason to disallow it for companion objects in particular.

    One common use in Scala is for factories: e.g. Seq, List, Vector etc. companion objects all extend TraversableFactory so you can write code working with a TraversableFactory and pass any of them to construct the type you want. E.g.

    def build[CC[X] <: Traversable[X] with GenericTraversableTemplate[X, CC], A](factory: TraversableFactory[CC])(elems: A*) = factory(elems)
    
    // build(List)(1,2,3) == List(1, 2, 3)
    // build(Set)(1,2,3) == Set(1, 2, 3)
    

    Similarly, all case class companion objects extend function types.