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

前端 未结 2 2033
北荒
北荒 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:15

    Assuming below that you really need EventHandler as a separate interface (e.g. for Java interop). If you don't, you can simply use a type alias (since Kotlin 1.1):

    typealias EventHandler = (T) -> Unit
    

    In this case a simple lambda will work right away.

    But if you don't want to use a type alias, the issue still stands. 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.

    To support this syntax:

    Events.handler(Handshake::class, EventHandler { println(it.sent) })
    

    You can define a function named EventHandler:

    fun  EventHandler(handler: (T) -> Unit): EventHandler 
        = object : EventHandler { 
            override fun handle(event: T) = handler(event) 
        }
    

    To support this syntax:

    Events.handler(Handshake::class, { println(it.sent) })
    

    or this:

    Events.handler(Handshake::class) { println(it.sent) }
    

    You need to overload the handler function to take a function instead of EventHandler:

    fun  Events.handler(eventType: Class, handler: (T) -> Unit) = EventHandler(handler)
    

提交回复
热议问题