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 */ }
}

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 interface

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个方法实现

Kotlin相关问答推荐

创建具有共同父类型的两种不同类型对象的列表的最有效方法是什么?

判断字符串是否除了.&" ",","@""""

在构造函数中创建内部类实例时,只能使用包含类的接收器调用内部类的构造函数

Criteria Api 中的 Kotlin 泛型

找不到有效的 Docker 环境

Android Jetpack Compose:在空的 Compose 活动中找不到 OutlinedTextField (Material3)

判断 Kotlin 变量是否为函数

使用 Kotlin 协程时 Room dao 类出错

为什么 Kotlin 需要函数引用语法?

使用 clear() 删除 EncryptedSharedPreferences 不起作用

更新到版本4.10.1/4.10.2后 Gradle 同步失败

如何在Kotlin中创建填充空值的通用数组?

Android 与 Kotlin - 如何使用 HttpUrlConnection

Kotlin 接口属性:只需要公共 getter 而没有公共 setter

在Kotlin中为Android编写库会有开销吗?

如何为 Java 调用者声明返回类型为void的 Kotlin Lambda?

Dagger +Kotlin 不注入

导航架构组件 - 未生成 DestinationFragmentArgs

Recyclerview: listen to padding click events

Android room DAO 接口不适用于继承