对象快速继承和接口含义

Object quick inheritance and Interface meaning

我在 Kotlin: Object 文档中找到了一个示例:

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

interface B {...}

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

所以我用更有意义的名称实现了该示例,但我不知道以逗号分隔的超类型列表与对象之间的接口的原因是什么?

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 ???
}

您已经创建了一个匿名 class 的实例,它继承自 class Ball,同时实现了接口 Toy.

但是,这两种类型都是排他性的,即。 Ball 不是 Toy(在您的示例中),因此您不能在对 Ball 的引用上调用 play()

你是对的,如果 A(或 Ball ) 没有实现它。

从该接口继承可能只是在此处添加,因此本示例旨在展示如何将构造函数参数传递给超类,也可以非常快速地展示从多个类型继承。或者至少这是我从随附的文本中收集到的内容:

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.


要解决无法在此处将创建的 object 用作 B(或 Toy)的问题:这不会使语言功能变得无用,因为创建的 object 仍然可以通过转换通过其多个接口使用。例如,在您的示例中,您可以这样做:

(ball as Toy).play()

或者在原始示例中,您可以创建类型 Any,然后根据需要转换为不同的接口。