在Kotlin中调用操作符&运算符重载

我了解了Invoke操作符,

a()相当于a.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 Parser.invoke extension function 

使用调用操作符的最多方式是将其用作Factory Method ,例如:

 // v--- call the invoke(String) operator val data1 = Data("1") // v--- call the invoke() operator val default = Data() // v-- call the constructor val data2 = Data(2) 

这是因为伴侣对象是Kotlin中的一个特殊对象。 事实上,上面的代码Data("1")被翻译成下面的代码:

 val factory:Data.Companion = Data // v-- the invoke operator is used here val data1:Data = factory.invoke("1") 

 class Data(val value: Int) { companion object { const val DEFAULT =-1 // v--- factory method operator fun invoke(value: String): Data = Data(value.toInt()) // v--- overloading invoke operator operator fun invoke(): Data = Data(DEFAULT) } }