我了解了 Invoke 运算符,
a()
等价于 a.invoke()
关于 Invoke 运算符的内容是否比请解释的更多。此外,我没有得到任何 Invoke 运算符重载的示例。
调用运算符重载可能吗?如果可能的话,任何人都可以用一个例子解释一下 Invoke 运算符重载吗?我对此一无所知。
提前致谢。
最佳答案
是的,您可以重载 invoke
。这是一个例子:
class Greeter(val greeting: String) {
operator fun invoke(target: String) = println("$greeting $target!")
}
val hello = Greeter("Hello")
hello("world") // Prints "Hello world!"
除了@holi-java 所说的之外,重写 invoke
对于任何有明确操作的类都非常有用,可以选择获取参数。使用这种方法作为 Java 库类的扩展函数也很棒。
例如,假设您有以下 Java 类
public class ThingParser {
public Thing parse(File file) {
// Parse the file
}
}
然后,您可以像这样在 Kotlin 的 ThingParser 上定义扩展:
operator fun ThingParser.invoke(file: File) = parse(file)
然后像这样使用它
val parser = ThingParser()
val file = File("path/to/file")
val thing = parser(file) // Calls ThingParser.invoke extension function
关于operator-overloading - 在 Kotlin 中调用运算符和运算符重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45173677/