Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invoke Operator & Operator Overloading in Kotlin

I get to know about the Invoke operator that,

a() is equivalent to a.invoke()

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

Is Invoke operator overloading is 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.

like image 328
Avijit Karmakar Avatar asked Jul 18 '17 17:07

Avijit Karmakar


People also ask

What is invoke () in Kotlin?

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.

What does the operator do in Kotlin?

An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. Kotlin is rich in built-in operators and provide the following types of operators: Arithmetic Operators.

What does ?: Mean in Kotlin?

In certain computer programming languages, the Elvis operator ?: is a binary operator that returns its first operand if that operand is true , and otherwise evaluates and returns its second operand.

Does Kotlin support Operatoroverloading?

Since Kotlin provides user-defined types, it also provides the additional functionality to overload the standard operators, so that working with user-defined types is easier. All of the unary, binary, relational operators can be overloaded.


1 Answers

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 
like image 110
Ruckus T-Boom Avatar answered Sep 22 '22 17:09

Ruckus T-Boom