How to create an instance of anonymous interface in Kotlin?

Peter Lamberg picture Peter Lamberg · Jun 7, 2016 · Viewed 43.5k times · Source

I have a third party Java library which an object with interface like this:

public interface Handler<C> {
  void call(C context) throws Exception;
}

How can I concisely implement it in Kotlin similar to Java anonymous class like this:

Handler<MyContext> handler = new Handler<MyContext> {
   @Override
   public void call(MyContext context) throws Exception {
      System.out.println("Hello world");
   }
}

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

Answer

miensol picture miensol · Jun 7, 2016

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

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

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")  }
}