How to create an instance of anonymous class of abstract class in Kotlin?

后端 未结 1 1222
借酒劲吻你
借酒劲吻你 2020-11-29 02:12

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

In java I can do:

KeyListener keyListener = new         


        
相关标签:
1条回答
  • 2020-11-29 02:38

    From the official Kotlin language documentation:

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

    Applied to your problem at hand:

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

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

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

    0 讨论(0)
提交回复
热议问题