Lambda implementation of interface in kotlin

后端 未结 3 1836
一生所求
一生所求 2020-12-03 13:41

What would be the equivalent of that code in kotlin, nothing seems to work of what I try:

public interface AnInterface {
    void doSmth(MyClass inst, int nu         


        
相关标签:
3条回答
  • 2020-12-03 14:04

    You can use an object expression

    So it would look something like this:

    val impl = object : AnInterface {
        override fun(doSmth: Any, num: Int) {
            TODO()
        }
    }
    
    0 讨论(0)
  • 2020-12-03 14:11

    If AnInterface is Java, you can work with SAM conversion:

    val impl = AnInterface { inst, num -> 
         //...
    }
    

    Otherwise, if the interface is Kotlin...

    interface AnInterface {
         fun doSmth(inst: MyClass, num: Int)
    }
    

    ...you can use the object syntax for implementing it anonymously:

    val impl = object : AnInterface {
        override fun doSmth(inst:, num: Int) {
            //...
        }
    }
    
    0 讨论(0)
  • 2020-12-03 14:18

    If you're rewriting both the interface and its implementations to Kotlin, then you should just delete the interface and use a functional type:

    val impl: (MyClass, Int) -> Unit = { inst, num -> ... }
    
    0 讨论(0)
提交回复
热议问题