Kotlin's 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:
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:
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.