Invoke Operator & Operator Overloading in Kotlin

前端 未结 3 556
北海茫月
北海茫月 2020-12-30 23:39

I get to know about the Invoke operator that,

a() is equivalent to a.invoke()

Is there anything more regarding Invoke operator the

3条回答
  •  被撕碎了的回忆
    2020-12-31 00:06

    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
    

提交回复
热议问题