Invoke Operator & Operator Overloading in Kotlin

Viewed 37739

I get to know about the Invoke operator that,

a() is equivalent to a.invoke()

Is there anything more regarding Invoke operator than please explain. Also, I did not get any example of Invoke operator overloading.

Is Invoke operator overloading possible? If possible then can anyone please explain about the Invoke operator overloading with an example? I did not get anything regarding this.

Thanks in advance.

5 Answers

Operator Function invoke() Kotlin provides an interesting function called invoke, which is an operator function. Specifying an invoke operator on a class allows it to be called on any instances of the class without a method name.

Let’s see this in action:

class Greeter(val greeting: String) {
    operator fun invoke(name: String) {
        println("$greeting $name")
    }
}

fun main(args: Array<String>) {
    val greeter = Greeter(greeting = "Welcome")
    greeter(name = "Kotlin")
    //this calls the invoke function which takes String as a parameter
}

A few things to note about invoke() here. It:

  • Is an operator function.
  • Can take parameters.
  • Can be overloaded.
  • Is being called on the instance of a Greeter class without method name.

In addition to the other answers:

It's possible to define a class extending an anonymous function.

class SpecialFunction : () -> Unit {}

In such case, the operator invoke is already defined, so it needs to be overriden:

class MyFunction : () -> Unit {
    override fun invoke() { println("Hi Mom") }
}

One more thing about syntax repercussions:

If such "functor" is called right after constructing it, you end up with double parentheses:

MyFunction()()

And, if such functor returns another functor, you may see some obscurities like

MyFunction()()()()()...

perhaps including parameters. This will not surprise anyone coming from the JavaScript world, though.

If you have some Python background,

you can think invoke in Kotlin as __call__ in Python.

By using this, you can "call" your object as if it's a function.

One difference is: you can overload invoke, but there is no official way to overload methods in Python.

Related