Kotlin classes implementing Functions
Graham Cox
Posted on January 2, 2019
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.
Posted on January 2, 2019
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 23, 2024