How to create an instance of anonymous interface in Kotlin?

前端 未结 4 1144
北海茫月
北海茫月 2020-12-02 09:49

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

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


        
相关标签:
4条回答
  • 2020-12-02 10:06

    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() {}
    })
    
    0 讨论(0)
  • 2020-12-02 10:10
         val obj = object : MyInterface {
             override fun function1(arg:Int) { ... }
    
             override fun function12(arg:Int,arg:Int) { ... }
         }
    
    0 讨论(0)
  • 2020-12-02 10:20

    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")  }
    }
    
    0 讨论(0)
  • 2020-12-02 10:24

    The simplest answer probably is the Kotlin's lambda:

    val handler = Handler<MyContext> {
      println("Hello world")
    }
    
    handler.call(myContext) // Prints "Hello world"
    
    0 讨论(0)
提交回复
热议问题