DEV Community

Graham Cox
Graham Cox

Posted on

Kotlin classes implementing Functions

Little trick that I discovered today.

As you probably know, in Kotlin - as in Java 8 - a Function is able to implement a Single Method Interface, as follows:

        Assertions.assertAll(
                Executable { Assertions.assertEquals(clientId, token.client) },
                Executable { Assertions.assertEquals(userId, token.user) },
                Executable { Assertions.assertEquals(NOW, token.issued) },
                Executable { Assertions.assertEquals(NOW.plus(duration), token.expires) },
                Executable { Assertions.assertEquals(setOf(GlobalScopes.ALL), token.scopes) }
        )

Each of those Executable entries is defining a function that matches the Executable interface.

However, the opposite is also true. You can write a class that can be used anywhere a particular function type is expected. For example:

class UUIDNonceGenerator : () -> String {
    /**
     * Generate the Nonce
     * @return the nonce
     */
    override operator fun invoke() = UUID.randomUUID().toString()
}

An instance of this class is usable anywhere that a function that takes 0 parameters and returns a string - a () -> String - is accepted.

The reasoning for this is actually quite sound. The class actually implements kotlin.jvm.functions.Function0<java.lang.String>, which is exactly what () -> String means. So it's actually just a class implementing an interface. It just so happens that this works both ways, so anything that also accepts a () -> String actually accepts a kotlin.jvm.functions.Function0<java.lang.String>, and thus the types match. Voila.

Not sure how useful this is, but it's there if you need it.

Top comments (0)