最近在 portal.kotlin-academy.com/#/ 上看到很多关于 Kotlin 的有趣的题目。个人觉得很适合 Kotlin 爱好者,感兴趣的小伙伴可自行查阅。
【有趣的 Kotlin 】系列记录自己对每一题的理解。
0x07:Composition
operator fun (() -> Unit).plus(f: () -> Unit) = {
this()
f()
}
fun main(args: Array<String>) {
({ print("Hello, ") } + { print("World") })()
}
以上代码,运行结果是什么?可选项:
- "Hello, World"
- Error: Expecting top-level declaration
- Error: Expression f cannot be invoked as a function
- Error: Unresolved reference (operator + not defined for this types)
- Works, but prints nothing
思考一下,记录下你心中的答案。
分析
上一篇文章我们提到过,Kotlin 中使用 operator 关键字用于修饰函数,表示该函数重载一个操作符或者实现一个约定。使用 operator 关键字修饰函数并且函数名只能为component1、component2、component3 … 时则是实现一个约定,即 解构 。
题目中这个操作符重载函数,我们分析下
重载函数的 receiver ,参数以及返回值均为函数类型
() -> Unit
再看看 main() 函数,对照上方操作符重载函数一起查阅。
所以,正确答案为
选项 1 :"Hello, World"
延伸
val aa = println("hello")
val a = { println("hello") }
fun b() = println("b")
fun c() = { println("c") }
fun d(e: () -> Unit) {
e()
}
fun f(e: () -> Unit) = {
e()
}
fun main(){
println(aa)
println(a)
b()
c()()
c().invoke()
d(c())
f(c())()
}
随机手写一题,望各位不吝赐教。
总结
Function:kotlinlang.org/docs/functi…
Lambdas:kotlinlang.org/docs/lambda…
Inline functions:kotlinlang.org/docs/inline…