一起来学Kotlin:概念:23. Invoke operator(运算符)介绍
Kotlin 的一个有趣特性是能够定义 Invoke
运算符。 一句话总结:当我们在类上指定 Invoke
运算符时,可以在该类的任何实例上调用它而无需其方法名称!说白了就是让类里面的某些特殊函数调用更加简洁。
一个例子
这里,我们先列举一些例子,
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())
}
}
我们怎么使用呢?
fun main(args: Array<String>) {
val urlScraper = UrlScraper(Socket())
urlScraper("www.google.com") //calls the invoke method you specified
}
UrlScraper
明明是一个类,这里写的像一个函数一样。这就是 Invoke
运算符的作用。
另一个例子
不仅仅是 Invoke
,get
也可以实现类似的功能:
data class TestBean(val name: String,val age: Int){
//定义非常简单 使用operator重载运算符get方法
operator fun get(index : Int): Any{
return when(index) {
0 -> name
1 -> age
else -> name
}
}
}
我们在使用时,testBean.get(index)
也可以被简化为 testBean.get[index]
。
val testBean = TestBean("zyh",20)
testBean.get(0)
testBean[0]
对于 Invoke
运算符的另一个例子:
data class TestBean(val name: String,val age: Int){
//重载定义invoke方法
operator fun invoke() : String{
return "$name - $age"
}
}
下面两种调用形式:
val testBean = TestBean("zyh",20)
//正常调用
testBean.invoke()
//约定后的简化调用
testBean()