kotlinfunctional-interfacehttp4k

How to understand Kotlin Functional Interface with companion object inside?


I would like to get some help to understand a Kotlin code snippet about functional interface used in Http4k org.http4k.core package

typealias HttpHandler = (Request) -> Response

fun interface Filter : (HttpHandler) -> HttpHandler {
    companion object
}

I don’t understand the Filter interface, especially the companion object part. A typical functional interface is like this

fun interface IntPredicate {
    fun accept(i: Int): Boolean
}

And you can create a lambda isEven

val isEven = IntPredicate { it % 2 == 0 }

According to this simple example, it looks like the interface Filter extends another interface (HttpHandler) -> HttpHandler? Then it defines a function signature companion object? Is this correct? What does the part companion object really mean?


Solution

  • Filter extends (HttpHandler) -> HttpHandler and the function type (HttpHandler) -> HttpHandler has a single abstract method (operator) - invoke - implicitly declared, like this:

    operator fun invoke(HttpHandler): HttpHandler
    

    So that is the function signature for the functional interface, not companion object.

    companion object means what it has always meant - a companion object declaration. The companion object might seem empty, just from looking at the code you showed, and it makes one wonder what its purpose is. If you have removed the declaration, the functional interface would still have compiled, and can be used just like a functional interface representing the function type (HttpHandler) -> HttpHandler.

    If you look further down the file, however, you'll see that there is (at least) one extension function declared on the companion object:

    val Filter.Companion.NoOp: Filter get() = Filter { next -> { next(it) } }
    

    This allows you to do val noOp = Filter.NoOp for example, so the companion object isn't that pointless.