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

Technology CommunityCategory: KotlinHow to create an instance of anonymous class of abstract class in Kotlin?
VietMX Staff asked 3 years ago
Problem

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

In java I can do:

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

How to do the same in Kotlin?

Sometimes we need to create an object of a slight modification of some class, without explicitly declaring a new subclass for it. Kotlin handles this case with object expressions and object declarations.

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