How to create an instance of anonymous class of abstract class in Kotlin?
JavaAbstract ClassKotlinJava Problem Overview
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?
Java Solutions
Solution 1 - Java
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][1] can be used to simplify this statement even further:
val keyListener = KeyAdapter { keyEvent ->
// ...
}
Please also note [this discussion][2] about the different usage of interfaces defined in Java and Kotlin.
[1]: https://kotlinlang.org/docs/reference/java-interop.html#sam-conversions "SAM Conversions" [2]: https://discuss.kotlinlang.org/t/kotlin-and-sam-interface-with-two-parameters/293
Solution 2 - Java
In Java
private Comparator<Integer> comparator = new Comparator<Integer>(){
@Override
public int compare(Integer o1, Integer o2) {
return o1.compareTo(o2);
}
};
in Kotlin
private val comparator = object: Comparator<Int> {
override fun compare(o1: Int, o2: Int): Int {
return o1.compareTo(o2)
}
}
But because Comparator is a FunctionalInterface we can take advantage of SAM conversions and write
private val comparator = Comparator<Int> { o1, o2 -> o1.compareTo(o2) }
Please note that SAM feature only works for Functional
interfaces defined in java, if you need to create object
of a kotlin interface
with single method then you will have to use object
syntax.