调用运算符和Kotlin中的运算符重载 [英] Invoke Operator & Operator Overloading in Kotlin

查看:211
本文介绍了调用运算符和Kotlin中的运算符重载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我了解Invoke运算符

I get to know about the Invoke operator that,

a()等效于a.invoke()

还有关于Invoke运算符的更多信息,然后请解释.另外,我没有得到Invoke运算符重载的任何示例.

Is there anything more regarding Invoke operator then please explain. Also, I did not get any example of Invoke operator overloading.

是否可以调用运算符重载?如果可能的话,任何人都可以用示例说明有关Invoke运算符重载的信息.我对此一无所获.

Is Invoke operator overloading is possible? If possible then can anyone please explain about the Invoke operator overloading with an example. I did not get anything regarding this.

谢谢.

推荐答案

是的,您可以重载invoke.这是一个示例:

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!"

除了@ holi-java所说的以外,对于任何有明确动作(可选地带参数)的类,重写invoke也是有用的.用这种方法作为Java库类的扩展功能也很棒.

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.

例如,假设您具有以下Java类

For example, say you have the following Java class

public class ThingParser {
    public Thing parse(File file) {
        // Parse the file
    }
}

在Kotlin中,您可以像这样在ThingParser上定义扩展名:

In Kotlin, you can define an extension on ThingParser like so:

operator fun ThingParser.invoke(file: File) = parse(file)

并像这样使用它

val parse = ThingParser()
val file = File("path/to/file")
val thing = parse(file)  // Calls Parser.invoke extension function

这篇关于调用运算符和Kotlin中的运算符重载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆