How to create an instance of anonymous interface in Kotlin?

有些话、适合烂在心里 提交于 2019-12-28 03:32:04

问题


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"

回答1:


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



回答2:


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

                        override fun OnPermissionsDeniedForever() {}
})



回答3:


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

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



回答4:


The simplest answer probably is the Kotlin's lambda:

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

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


来源:https://stackoverflow.com/questions/37672023/how-to-create-an-instance-of-anonymous-interface-in-kotlin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!