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.
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With