DEV Community

Graham Cox
Graham Cox

Posted on

4 2

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.

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay