Kotlin:使用getter实现问题的实现接口

Jag*_*uar 4 kotlin

我正在尝试使用与实现类的构造函数参数名称匹配的getter方法来实现接口。

interface Car{
    fun getModel(): Int
}

class Honda(val model: Int): Car {
    override fun getModel(): Int {

    }
}
Run Code Online (Sandbox Code Playgroud)

如果Honda未实现getModel(),则会Accidental Override出现错误。如果Honda执行getModel(),则会出现Platform declaration clash错误。

我可以在Honda构造函数中更改参数的名称,从而解决了该问题,但感觉像是一个多余的getter方法。

interface Car{
    fun getModel(): Int
}

class Honda(val modelParam: Int): Car {
    override fun getModel() = modelParam
}
Run Code Online (Sandbox Code Playgroud)

有没有更好的方法来实现这样的接口?

Paw*_*wel 5

您可以在interface中声明属性

interface Car{
    val model : Int
}
Run Code Online (Sandbox Code Playgroud)

然后在实现/构造函数中,您需要添加override关键字。

class Honda(override val model : Int): Car
Run Code Online (Sandbox Code Playgroud)


Ale*_*nov 5

For case where the accepted answer isn't applicable because you can't change the interface, or the interface is a Java one,

class Honda(private val model: Int): Car {
    override fun getModel(): Int = model
}
Run Code Online (Sandbox Code Playgroud)

For a Java interface, it can still be accessed as .model in Kotlin.