Explain Codes LogoExplain Codes Logo

How to create an instance of anonymous interface in Kotlin?

kotlin
lambda
functional-interfaces
type-safe-builder-pattern
Anton ShumikhinbyAnton Shumikhin·Feb 16, 2025
TLDR

In Kotlin, you can instantiate an anonymous interface by using object expression. You define the interface in the variable declaration as follows:

val myInterfaceInstance = object : MyInterface { override fun myFunction() { // Your code goes here } } myInterfaceInstance.myFunction()

In the above snippet, you declare a variable with val, assign it a name, and use object : along with the interface name, then provide the function overrides in the braces { }.

Instantiate a SAM interface with a lambda

A single abstract method (SAM) interface can be represented too using a lambda. When the interface you're implementing only has one method, Kotlin allows for a much more compact form:

fun interface MySAMInterface { fun myAction() } val myInterfaceInstance = MySAMInterface { println("Look ma, no hands!") // Team no hands } myInterfaceInstance.myAction()

It's equivalent to an anonymous instance but with a lambda for simplicity. Be aware that SAM conversions are only applicable for interfaces with a single abstract method.

Lambdas and function interfaces: Less is more

Lambdas in Kotlin offer a neat way of implementing functional interfaces. You can use a lambda to create instances of functional interfaces, making your code concise and easy to read.

val myHandler = Handler { myContext: MyContext -> println("Daemon thread? More like 'dey-moan' thread! $myContext") // Developers humor } myHandler.call(MyContext())

The above assumes that Handler is a functional interface or a SAM interface from Java. By using lambdas, you can say goodbye to unnecessary verbosity.

When you've more than one method in an interface

When you are dealing with multiple methods in an interface, you can't use the SAM conversions. Here, you need to use the keyword object:

interface MyMultipleMethodsInterface { fun methodOne() fun methodTwo() } val myInterfaceInstance = object : MyMultipleMethodsInterface { override fun methodOne() { // Implementation for methodOne } override fun methodTwo() { // Implementation for methodTwo } }

Remember to override all the abstract methods in the interface.

Practical applications and specific scenarios

How Android utilizes anonymous classes

In Android development, instantiating anonymous classes is common in handling events, such as button clicks. As these events are often single-method interfaces, SAM conversions can be effectively utilized.

button.setOnClickListener { // Exactly what the button signed up for 🖲️ }

The code block above is Kotlin's syntax sugar to implement the OnClickListener interface that is equipped with a single abstract method, well-known as the onClick.

Harnessing the power of type-safe builders

Using Kotlin's type-safe builder pattern, you can create DSLs and thereby use anonymous interfaces. Following is an example:

val html = html { head { title("HTML builders > Web builders") // Who needs Wix or Squarespace? We've Kotlin } body { a(href = "http://kotlinlang.org") { /* It's not spam if it's Kotlin */ +"Kotlin" } } }

In this case, each such function like html, head, body, a, etc., most likely have a builder interface, which might be an instance of anonymous interface internally.

Problematic areas and workarounds

When making a transition from Java to Kotlin, you might encounter issues with Java SAM interfaces compatibility. Ensure that the Kotlin equivalent is marked as a fun interface to maintain the concise lambda syntax.

Typos in method signatures when declaring an anonymous class can lead to new methods, instead of overriding the interface methods. Always use the override keyword to avoid such situations. Remember, compiler is your lighthouse.