Kotlin: Use a lambda in place of a functional interface?

前端 未结 2 2031
北荒
北荒 2020-12-02 17:01

In Java we can do this Events.handler(Handshake.class, hs -> out.println(hs));

In Kotlin however I am trying to replicate the behavior to replace thi

2条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-02 17:14

    A lot of nice things has happened to Kotlin since @andrey-breslav posted the answer. He mentions:

    It is that Kotlin only does SAM-conversion for functions defined in Java. Since Events.handler is defined in Kotlin, SAM-conversions do not apply to it.

    Well, that's no longer the case for Kotlin 1.4+. It can use SAM-conversion for Kotlin functions if you mark an interface as a "functional" interface:

    // notice the "fun" keyword
    fun interface EventHandler {
        fun handle(event: T)
    }
    

    You can read the YouTrack ticket here: https://youtrack.jetbrains.com/issue/KT-7770. There's also an explanation why Kotlin needs a marker for such interfaces unlike Java (@FunctionalInterface is only informational and has no effect on the compiler).

提交回复
热议问题