当前位置:网站首页>有趣的 Kotlin 0x07:Composition

有趣的 Kotlin 0x07:Composition

2022-07-28 15:42:00 AndroidKt

最近在 http://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") })()
}

以上代码,运行结果是什么?可选项:

  1. "Hello, World"
  2. Error: Expecting top-level declaration
  3. Error: Expression f cannot be invoked as a function
  4. Error: Unresolved reference (operator + not defined for this types)
  5. Works, but prints nothing

思考一下,记录下你心中的答案。

分析

上一篇文章我们提到过,Kotlin 中使用 operator 关键字用于修饰函数,表示该函数重载一个操作符或者实现一个约定。使用 operator 关键字修饰函数并且函数名只能为component1component2component3 … 时则是实现一个约定,即 解构

题目中这个操作符重载函数,我们分析下

函数类型

重载函数的 receiver ,参数以及返回值均为函数类型 () -> Unit

再看看 main() 函数,对照上方操作符重载函数一起查阅。

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:https://kotlinlang.org/docs/functions.html

Lambdas:https://kotlinlang.org/docs/lambdas.html

Inline functions:https://kotlinlang.org/docs/inline-functions.html

原网站

版权声明
本文为[AndroidKt]所创,转载请带上原文链接,感谢
https://onlyloveyd.blog.csdn.net/article/details/118227966