Is it possible in Kotlin to create an anonymous class implementing a certain interface and only implement the functions you'll need? For example I want to create a class implementing AnimationListener
which has 3 methods:
If I only want to use the onAnimationEnd
callback, can I just do something like this?
object : AnimationListener {
override fun onAnimationEnd() {
//my implementation
}
}
The way I've done this in Java was by creating a class which implemented the interface, just create anonymous class of that class and override the methods I need. I was hoping Kotlin has a better, less verbose, approach on this.
No, anonymous types cannot implement an interface. From the C# programming guide: Anonymous types are class types that consist of one or more public read-only properties. No other kinds of class members such as methods or events are allowed. An anonymous type cannot be cast to any interface or type except for object.
Anonymous class usually extends a subclass or implement an interface Functional Interface is simply an interface that has exactly one abstract method. For example, the interface Animal is a Functional Interface. You can annotate functional interfaces with @FunctionalInterface
Anonymous inner classes in method/constructor arguments are often used in graphical user interface (GUI) applications. To get you familiar with syntax lets have a look at the following program that creates a thread using this type of Anonymous Inner class However, constructors can not be declared in an anonymous class.
But anonymous Inner class can extend a class or can implement an interface but not both at a time.
I don't expect there's anything in Kotlin different to Java in this respect. You can, however, create your own interfaces that have default no-op implementation of methods you don't need :
interface AnimationEndListener : AnimationListener {
fun onAnimationStart() {}
fun onAnimationRepeat() {}
}
Then actual concrete implementation will extend AnimationEndListener
and override only what's needed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With