Search code examples
objectinheritanceinterfacekotlindelegation

Object quick inheritance and Interface meaning


I find in Kotlin: Object documentation an example:

open class A(x: Int) {
    public open val y: Int = x
}

interface B {...}

val ab: A = object : A(1), B {
    override val y = 15
}

So I implemented that example with more meaningful names and I have no clue what is the reason of the interface among the comma separated list of supertypes to the object?

interface Toy {
    fun play () {
        println("Play, play....")
    }
}

open class Ball(public open val color: String = "red") {}

val ball: Ball = object : Ball(), Toy {
    override val color : String = "blue"
    override fun play() {
        println("Bounce, bounce...")
    }
}

fun main(args: Array<String>) {
    println(ball.color)
    // no ball.play() here then why the interface in the example ???
}

Solution

  • You're correct, the interface B (or in your example, Toy) will not be directly accessible through this reference if A (or Ball) doesn't implement it.

    Inheriting from that interface is probably just added here so that this example intended to show how constructor parameters are passed to a superclass can also show off inheriting from multiple types very quickly. Or at least that's what I gather from the text accompanying it:

    If a supertype has a constructor, appropriate constructor parameters must be passed to it. Many supertypes may be specified as a comma-separated list after the colon.


    To get to the issue of not being able to use the created object as a B (or Toy) here: this doesn't make the language feature useless, since the created object can still be used through its multiple interfaces through casting. For example, in your example, you can do this:

    (ball as Toy).play()
    

    Or in the original example, you could make the type Any, and then cast to the different interfaces as needed.