How to create an instance of anonymous interface in Kotlin?

JavaLambdaKotlinAnonymous

Java Problem Overview


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"

Java Solutions


Solution 1 - Java

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

Solution 2 - Java

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() {}
})

Solution 3 - Java

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

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

Solution 4 - Java

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

Solution 5 - Java

The simplest answer probably is the Kotlin's lambda:

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

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPeter LambergView Question on Stackoverflow
Solution 1 - JavamiensolView Answer on Stackoverflow
Solution 2 - JavaAalapView Answer on Stackoverflow
Solution 3 - Javapruthwiraj.kadamView Answer on Stackoverflow
Solution 4 - JavaNickView Answer on Stackoverflow
Solution 5 - JavaPeter LambergView Answer on Stackoverflow