Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an instance of anonymous interface in Kotlin?

People also ask

Can you create an instance of an interface in Kotlin?

In Kotlin, we can create an object expression of an interface by implementing its abstract methods. This implementation technique is known as anonymous interface.

How do you make an anonymous object on Kotlin?

Creating Anonymous Objects From an Interface In Kotlin, as interfaces cannot have constructors, the object expression's syntax changes to: object : TheInterface { ... implementations ... } As the code above shows, our anonymous class has overridden the content property and implemented the print function.

How do I write an anonymous class on Kotlin?

In kotlin, we can achieve this by using the “Object” keyword; the object declaration contains properties, methods, and so on. However, mainly it does not allowed the constructor to create the object. Like that object, a keyword is used for to create the objects of the anonymous class known as the anonymous object.


Assuming the interface has only a single method you can make use of SAM.

val handler = Handler<String> { println("Hello: $it") }

Since version 1.4 Kotlin supports SAM for interfaces defined in Kotlin. That requires prefixing the interface keyword with fun

fun interface Handler<C> {
  fun call(context: C);
}

If you have a method that accepts a handler then you can even omit type arguments:

fun acceptHandler(handler:Handler<String>){}

acceptHandler(Handler { println("Hello: $it") })

acceptHandler({ println("Hello: $it") })

acceptHandler { println("Hello: $it") }

If the interface has more than one method the syntax is a bit more verbose:

val handler = object: Handler2<String> {
    override fun call(context: String?) { println("Call: $context") }
    override fun run(context: String?) { println("Run: $context")  }
}

I had a case where I did not want to create a var for it but do it inline. The way I achieved it is

funA(object: InterfaceListener {
                        override fun OnMethod1() {}

                        override fun OnMethod2() {}
})

     val obj = object : MyInterface {
         override fun function1(arg:Int) { ... }

         override fun function12(arg:Int,arg:Int) { ... }
     }

As of Kotlin 1.4 you can declare a functional interface:

fun interface Handler<C> {
  fun call(context: C);
}

and then you can create one concisely:

val handler = Handler<String> {
  println("Handling $it")
}

Demo


The simplest answer probably is the Kotlin's lambda:

val handler = Handler<MyContext> {
  println("Hello world")
}

handler.call(myContext) // Prints "Hello world"