Kotlin关于Unit,() -> Unit,闭包,函数返回的学习笔记

关键词: Kotlin,Unit,() -> Unit,闭包,函数返回

原本想了解一下Kotlin中的() -> Unit是什么意思,结果学习了一波Kotlin的函数闭包

以下是经过学习之后,自我思考,而做下的笔记,其中有很详细的函数分析

有什么问题可以在评论区和我聊。

// accumulate是一个无参数的,返回"函数类型"的,函数
// "accumulate()"表示:是一个无参数的,名为accumulate的函数,记作函数A
// "() -> Unit"表示;	这是一个无参数的,返回空值Unit的,函数类型,暂记作函数B
// 将这个函数B,"() -> Unit",作为返回值,即返回一个是“函数类型”的返回值
// 在函数accumulate()中,即返回这个东东,"{ println(count++) }",这个代码块,block
// 但是注意,此时,这个block,是不会运行里面的内容的
// 因为它仍表示为一个函数类型的对象,只有在这个函数类型对象后加一个"()"
// 这个block,才会被激活
fun accumulate():() -> Unit{
    var sum = 0
    return {
        println(sum++)
    }
}

fun main(args: Array<String>) {
    // 这里定义counting = accumulate(),则counting变为函数类型
    // 函数类型后面加一个"()",即可“被激活”
    // 多次调用counting,则表示,多次调用"同一个accumulate()"
    // 所以同一个accumulate()里的sum值保留,故能够累加
    // 但是,没有被申明的accumulate(),则分别视作单独的函数
    // 不具备累加的能力
    val counting = accumulate()
    counting()  		// 输出结果:0
    counting()  		// 输出结果:1
    counting()  		// 输出结果:2
    accumulate()()		// 输出结果:0
    accumulate()()		// 输出结果:0
    accumulate()()		// 输出结果:0

    println("counting: "+counting)			
    //                 输出结果: counting: Function0<kotlin.Unit>

    println("counting(): "+counting())		
    // 先输出: 3;	   后输出:    counting(): kotlin.Unit

    println("accumulate(): "+accumulate())	
    //                 输出结果: accumulate(): Function0<kotlin.Unit>
}
复制代码

输出结果:

0
1
2
0
0
0
counting: Function0<kotlin.Unit>
3
counting(): kotlin.Unit
accumulate(): Function0<kotlin.Unit>
复制代码

 以下是其他例子测试:

fun main(args: Array<String>) {
   val test = if (2 > 1) {
       println("true")	
   } else {
       println("false")
   }
   // 其实这里test,也是一个函数,返回Unit的函数,
   println(test)               //先输出: true; 后输出:kotlin.Unit
   println(test1("123"))		//先输出: 123;  后输出:kotlin.Unit
   test1("sfgfdsgfgsdgsdg")    //输出: sfgfdsgfgsdgsdg
}

fun test1(str:String){
   println(str)	
}
复制代码

 测试test1函数:

// 测试1
fun test1(str:String):() -> Unit{
  println(str)
}
// 报错:A 'return' expression required in a function with a block body ('{...}')
复制代码
// 测试2
fun test1(str:String): Unit{
   println(str)
}
// 无异常,证明在Kotlin中,可以省略": Unit"
复制代码

csdn同一作者

猜你喜欢

转载自juejin.im/post/6984701371932999716