Fares TP
Fares TP

Reputation: 11

Custom Class Implement a Function Type

Found this in kotlin documentation about function and lambda

class IntTransformer: (Int) -> Int {
    override operator fun invoke(x: Int): Int = TODO()
}

val intFunction: (Int) -> Int = IntTransformer()

In this page, it says that you can implement function type to class like an interface. How does it work? Can you give me some explanation every each part and give me an example how this is done?

From what I understand, IntTransformer expand/implement anonymous function that takes int as argument and output type, but I still didn't know how does it work...

Thanks

Upvotes: 0

Views: 259

Answers (1)

Tenfour04
Tenfour04

Reputation: 93581

You can think of a function type sort of like an interface that has a single function named invoke with the parameters and return type matching its definition.

So

(Int) -> String

is very much like

interface Foo {
    operator fun invoke(param: Int): String
}

And so if a class inherits from (Int) -> String, you would do it in exactly the same way as you would to inherit Foo above. You could say the function inheritance is more versatile, because it allows your class to be passed around as a functional argument directly instead of having to get a reference to its invoke function using ::invoke.

Upvotes: 1

Related Questions