Avi*_*kar 7 operator-overloading kotlin
我开始了解Invoke运算符,
a() 相当于 a.invoke()
还有关于Invoke运算符的更多信息请解释.另外,我没有得到任何Invoke运算符重载的例子.
是否可以调用操作符重载?如果可能的话,任何人都可以通过示例解释Invoke运算符重载.我对此没有任何意见.
提前致谢.
Ruc*_*oom 17
是的,你可以超载invoke.这是一个例子:
class Greeter(val greeting: String) {
operator fun invoke(target: String) = println("$greeting $target!")
}
val hello = Greeter("Hello")
hello("world") // Prints "Hello world!"
Run Code Online (Sandbox Code Playgroud)
除了@ holi-java所说的,覆盖invoke对任何有明确动作的类都有用,可选择带参数.使用这种方法作为Java库类的扩展函数也很棒.
例如,假设您有以下Java类
public class ThingParser {
public Thing parse(File file) {
// Parse the file
}
}
Run Code Online (Sandbox Code Playgroud)
在Kotlin中,您可以在ThingParser上定义一个扩展名,如下所示:
operator fun ThingParser.invoke(file: File) = parse(file)
Run Code Online (Sandbox Code Playgroud)
并像这样使用它
val parser = ThingParser()
val file = File("path/to/file")
val thing = parser(file) // Calls Parser.invoke extension function
Run Code Online (Sandbox Code Playgroud)
小智 17
运算符函数 invoke() \nKotlin 提供了一个有趣的函数,称为invoke,它是一个运算符函数。在类上指定调用运算符允许在没有方法名称的情况下在类的任何实例上调用它。
\n让\xe2\x80\x99s 看看它的实际效果:
\nclass Greeter(val greeting: String) {\n operator fun invoke(name: String) {\n println("$greeting $name")\n }\n}\n\nfun main(args: Array<String>) {\n val greeter = Greeter(greeting = "Welcome")\n greeter(name = "Kotlin")\n //this calls the invoke function which takes String as a parameter\n}\nRun Code Online (Sandbox Code Playgroud)\n这里有一些关于invoke()需要注意的事情。它:
\n// 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)
Run Code Online (Sandbox Code Playgroud)
这是因为伴侣对象是Kotlin中的特殊对象.实际上,Data("1")上面的代码被翻译成如下代码:
val factory:Data.Companion = Data
// v-- the invoke operator is used here
val data1:Data = factory.invoke("1")
Run Code Online (Sandbox Code Playgroud)
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)
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6166 次 |
| 最近记录: |