I get to know about the Invoke operator that,
a()
is equivalent to a.invoke()
Is there anything more regarding Invoke operator the
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 parse = ThingParser()
val file = File("path/to/file")
val thing = parse(file) // Calls Parser.invoke extension function