Invoke Operator & Operator Overloading in Kotlin

Yes, you can overload invoke. Here’s an example:

class Greeter(val greeting: String) {
    operator fun invoke(target: String) = println("$greeting $target!")

val hello = Greeter("Hello")
hello("world")  // Prints "Hello world!"

In addition to what @holi-java said, overriding invoke is useful for any class where there is a clear action, optionally taking parameters. It’s also great as an extension function to Java library classes with such a method.

For example, say you have the following Java class

public class ThingParser {
    public Thing parse(File file) {
        // Parse the file

You can then define an extension on ThingParser from Kotlin like so:

operator fun ThingParser.invoke(file: File) = parse(file)

And use it like so

val parser = ThingParser()
val file = File("path/to/file")
val thing = parser(file)  // Calls ThingParser.invoke extension function

Leave a Comment