问题描述
如果我只对 onSee
感兴趣而不关心其他事件怎么办?至少可以省略没有返回值的方法吗?
What if I am only interested in onSee
and do not care for other events? Can I at least omit the methods that have no return values?
interface EventHandler
{
fun onSee()
fun onHear()
fun onSmell()
fun onTouch()
fun onAwake()
fun onSleep()
}
fun addEventHandler(handler:EventHandler)
{
}
fun Main()
{
addEventHandler(object:EventHandler
{
override fun onSee()
{
print("I see.")
}
})
}
推荐答案
当然你只能实现一个接口方法,你要做的就是在接口声明中为其他方法提供一个默认实现
Sure you can only implement one interface method, all you have to do is to provide a default implementation for the other methods in the interface declaration
interface EventHandler {
fun onSee()
fun onHear() { /* default implementation */ }
fun onSmell(){ /* default implementation */ }
fun onTouch(){ /* default implementation */ }
fun onAwake(){ /* default implementation */ }
fun onSleep(){ /* default implementation */ }
}
现在当你创建这个接口的实例时,你只需要为onSee()
方法提供一个强制实现,rest是可选的
Now when you create an instance of this interface you only need to provide a compulsory implementation for onSee()
method, rest are optional
如果您不是原始界面的作者您可以扩展原始接口并为您想要的方法提供默认实现
If you're not the author of the original interfaceYou could extend the original interface and provide a default implementation for the methods you want
interface OnSeeEventHandler: EventHandler {
override fun onHear() { /* default implementation */ }
override fun onSmell(){ /* default implementation */ }
override fun onTouch(){ /* default implementation */ }
override fun onAwake(){ /* default implementation */ }
override fun onSleep(){ /* default implementation */ }
}
并使用OnSeeEventHandler
只提供onSee
方法实现
And use the OnSeeEventHandler
to provide only onSee
method imeplementation
这篇关于我可以省略我在 Kotlin 中不使用的接口方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!