markdown Kotlin的调用操作符

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了markdown Kotlin的调用操作符相关的知识,希望对你有一定的参考价值。

*Source:* [joshskeen](http://joshskeen.com/kotlins-invoke-operator/)

**- `invoke` operator:**

An interesting feature of the Kotlin language is the ability to define an "invoke operator". When you specify an invoke operator on a class, it can be called on any instances of the class without a method name! 
This trick seems especially useful for classes that really only have one method to be used.

For example, consider the following example:

```kotlin
class Socket  
class UrlScraper(val socket: Socket) {

    inner class ParseResult

    operator fun invoke(url: String): List<ParseResult> {
        //do cool stuff here with the url
        //eventually produces a list of ParseResult objects
        return listOf(ParseResult(), ParseResult())
    }
}
```

Once you specify the `invoke` operator, `UrlScraper` can perform it's work without any need for calling a method on it, since it does only one thing - scrapes a url! You can now simply pass the url to the instance like so:

```kotlin
fun main(args: Array<String>) {  
    val urlScraper = UrlScraper(Socket())
    urlScraper("www.google.com") //calls the invoke method you specified
}
```

I really like this trick, especially for classes that have just one public method - a `perform` method, for example - since it further simplifies how the API can be used.

以上是关于markdown Kotlin的调用操作符的主要内容,如果未能解决你的问题,请参考以下文章

深入kotlin - 与Java互操作:kotlin调用java

深入kotlin - 与Java互操作:java调用kotlin

markdown [Kotlin基本语法] #kotlin

深入kotlin - 与Java互操作:kotlin调用java

深入kotlin - 与Java互操作:kotlin调用java

深入kotlin - 与Java互操作:kotlin调用java