Skip to content
Advertisement

Using functional interfaces with function types in Kotlin

When calling Java code from Kotlin, there is SAM conversion so that Java code like this:

JavaScript

Can look like this:

JavaScript

Now, I’m working on a Kotlin project and I want to define a functional interface as an event listener:

JavaScript

In SomeClass I have a function to set the listener:

JavaScript

And when I create an instance of this class and try to invoke the setter function, I do it like so:

JavaScript

I’m aware that Kotlin has function types therefore doesn’t support SAM conversion from various sites such as this one.

I’ve read a little about function types but I have not used them before.

How would I rewrite my code so that I can invoke the setter function like this?

JavaScript

.

Advertisement

Answer

A function type looks like this:

JavaScript

In your case, instead of using the interface type, you could use (View, Int) -> Unit. It would look something like this:

JavaScript

Add names

In functional types you can also specify names for the parameters. This doesn’t change much under the hood but they can add some clarity here and in the calling code, which is nice.

JavaScript

Using a type alias

To avoid having to type (View, Int) -> Unit every time, you can define a typealias:

JavaScript

So that your code now looks like this again:

JavaScript

And to call it:

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement