How to create an instance of an anonymous interface in Kotlin?


Kotlin has been developed over JVM, hence it supports most of the features of JVM. Java provides a feature called anonymous inner classes to handle the cases where we have to create an object of a class with a slight modification, without declaring a new subclass. An anonymous inner class doesn't have a name; we define it directly at the instantiation line.

However, Kotlin uses object expressions to provide the same sub-class functionality. In Kotlin, we can create an object expression of an interface by implementing its abstract methods. This implementation technique is known as anonymous interface.

Example – Anonymous Interface in Kotlin

The following example demonstrates how we can implement an anonymous interface in Kotlin.

fun interface myInterface<T> {
   fun call(context: T)
}
fun main() {
   val a = myInterface<String> {
      println("This is implementation of $it")
   }
   a.call("myInterface")
}

Output

On execution, it will produce the following output −

This is implementation of myInterface

Updated on: 16-Mar-2022

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements