如何在Kotlin中创建一个抽象类的匿名类实例? [英] How to create an instance of anonymous class of abstract class in Kotlin?

查看:808
本文介绍了如何在Kotlin中创建一个抽象类的匿名类实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设 KeyAdapter 是一个抽象类,有几个方法可以被覆盖。

Assume that KeyAdapter is an abstract class with several methods that can be overridden.

在java中我可以执行:

In java I can do:

KeyListener keyListener = new KeyAdapter() {
    @Override public void keyPressed(KeyEvent keyEvent) {
        // ...
    }
};

如何在Kotlin中做同样的事情?

How to do the same in Kotlin?

推荐答案

来自官方Kotlin语言文档和Google上的首批点击之一:

From the official Kotlin language documentation and one of the first hits on Google:

window.addMouseListener(object : MouseAdapter() { 
    override fun mouseClicked(e : MouseEvent) { 
    // ... 
}

适用于您手头的问题:

val keyListener = object : KeyAdapter() { 
    override fun keyPressed(keyEvent : KeyEvent) { 
    // ... 
} 

正如Peter Lamberg指出的那样 - 如果匿名类实际上是功能接口的实现(即不是抽象类), SAM转换可用于进一步简化此声明:

As Peter Lamberg has pointed out - if the anonymous class is actually an implementation of a functional interface (i.e. not of an abstract class), SAM Conversions can be used to simplify this statement even further:

val keyListener = KeyAdapter { keyEvent ->
    // ...
}

请注意此讨论关于Java中定义的接口的不同用法和Kotlin。

Please also note this discussion about the different usage of interfaces defined in Java and Kotlin.

这篇关于如何在Kotlin中创建一个抽象类的匿名类实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆