我正在尝试使用与实现类的构造函数参数名称匹配的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)
有没有更好的方法来实现这样的接口?
您可以在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)
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.
| 归档时间: |
|
| 查看次数: |
272 次 |
| 最近记录: |