How to create an instance of an anonymous class of an abstract class in Kotlin?
To create an instance of an abstract class in Kotlin, you use an object expression:
In this instance, you override the abstract methods using the braces {}
to define your anonymous class. This is the easiest method to create an anonymous class in Kotlin.
Breakdown of object expressions
When to roll with an object expression
Use object expressions when you need a modified class instance for a one-time special occasion, for example, an abstract class or an interface, without declaring a new subclass. The equivalent of dressing up for your cousin's wedding.
Java and Kotlin: Apples and Oranges
In Java, anonymous classes are commonly used for event listeners for GUI elements. Kotlin, however, uses the object
keyword, providing cleaner code. Here's a comparison:
You can see the Kotlin code has left out the superfluous sugar, simplifying the syntax.
Single Abstract Method (SAM) conversions
For Singular Sensation interfaces a.k.a. functional interfaces that have only a single method, Kotlin has a neat trick: SAM conversions. This uses a lambda expression for neater code.
Note: SAM conversion is available with Java interfaces in Kotlin, but not Kotlin's own interfaces.
Advanced scenarios
Joining two interface parties
Kotlin lets you implement multiple interfaces within an anonymous class:
Doppelgänger event: extending a class and implementing an interface
Kotlin lets you extend a class and implement an interface at the same time within an anonymous class, effectively solving the problem by proudly wearing both hats!
Property override in anonymous classes
You can override properties in Kotlin's anonymous classes, opening the door to per-instance customization.
Be aware and beware!
SAM conversions and Kotlin interfaces
A common pitfall is trying to apply SAM conversions to Kotlin-defined interfaces. It's not currently possible:
To reach similar functionality in Kotlin, consider using functional types or inline classes.
Inline functions and object expressions
Object expressions are a no-no inside inline functions, unless they implement an interface marked as a functional interface with the fun
keyword:
A simple workaround is to use a lambda expression with a functional interface.
Property initialization in object expressions
Properties in an object expression get initialized when the class is instantiated. Be cautious!
Was this article helpful?