Kotlin, Unit, () -> Unit, closure, function return

Trying to find out what () -> Unit in Kotlin means, but learning a wave of Kotlin’s function closures

The following is the notes I made after studying and thinking about myself, with a detailed function analysis

Let me know in the comments section if you have any questions.

Accumulate is a function that returns "function type" without arguments
// "accumulate()" means that there is an unnamed accumulate function called accumulate. Call it function A
// "() -> Unit"; This is the type of a no-argument function that returns a null value of Unit, which I'll call function B for now
// take the function B, "() -> Unit", as the return value, i.e. return a value that is "function type"
// inside the function accumulate(), which returns this thing, "{println(count++)}", the code block, block
// But notice that at this point, the block will not run its contents
// Because it is still represented as an object of function type, only the function type object is followed by a "()".
// This block will be activated
fun accumulate(a): () - >Unit{
    var sum = 0
    return {
        println(sum++)
    }
}

fun main(args: Array<String>) {
    // accumulate()
    // The function type can be activated by adding a "()" after it.
    // counting is called accumulate().
    Sumsum-accumulate () = sumsum-accumulate ()
    Accumulate (), which is not declared, is treated as a separate function
    // Do not have the ability to add
    val counting = accumulate()
    counting()  		// Output: 0
    counting()  		// Output: 1
    counting()  		// Output: 2
    accumulate()()		// Output: 0
    accumulate()()		// Output: 0
    accumulate()()		// Output: 0

    println("counting: "+counting)			
    // Counting: Function0
      

    println("counting(): "+counting())		
    // First output: 3; Counting (): kotlin.unit

    println("accumulate(): "+accumulate())	
    Accumulate (): Function0< kotlin.unit >
}
Copy the code

Output result:

0
1
2
0
0
0
counting: Function0<kotlin.Unit>
3
counting(): kotlin.Unit
accumulate(): Function0<kotlin.Unit>
Copy the code

Here are other sample tests:

fun main(args: Array<String>) {
   val test = if (2 > 1) {
       println("true")}else {
       println("false")}// Test is a function that returns Unit.
   println(test)               // First output: true; Last output: kotlin.unit
   println(test1("123"))		// first output: 123; Last output: kotlin.unit
   test1("sfgfdsgfgsdgsdg")    // Output: SFGFDSGFGSDGSDG
}

fun test1(str:String){
   println(str)	
}
Copy the code

Test test1 function:

/ / test 1
fun test1(str:String): () - >Unit{
  println(str)
}
A 'return' expression required in A function with A block body ('{... } ')
Copy the code
/ / test 2
fun test1(str:String): Unit{
   println(str)
}
// Kotlin can omit ": Unit"
Copy the code

Same author of CSDN