官术网_书友最值得收藏!

Function return

To return a value from a function, we use the return keyword with the value or expression we want to return:

    fun addTwoNumbers(a: Int, b: Int): Int { 
      return a + b 
    } 

Note that we specified the return value of the function. By default, return returns from the nearest enclosing function or anonymous function. So, in a nested function, this will return from the innermost function only:

    fun largestNumber(a: Int, b: Int, c: Int): Int { 
      fun largest(a: Int, b: Int): Int { 
        if (a > b) return a 
          else return b 
      } 
      return largest(largest(a, b), largest(b, c)) 
    }

In this somewhat contrived example, the largest nested function returns only from itself. If the innermost function is an anonymous function, then that still counts for return purposes:

    fun printLessThanTwo() { 
      val list = listOf(1, 2, 3, 4) 
      list.forEach(fun(x) { 
        if (x < 2) println(x) 
        else return 
      }) 
      println("This line will still execute") 
    } 

If we need to return a value from a closure, then we need to qualify the return with a label; otherwise, the return would be for the outer function. A label is just a string that ends with @:

    fun printUntilStop() { 
      val list = listOf("a", "b", "stop", "c") 
      list.forEach stop@ { 
        if (it == "stop") return@stop 
        else println(it) 
      } 
    } 

We don't need to specify the label, in which case an implicit label can be used. Implicit labels are the name of the function that accepted the closure. If a label is defined, then the implicit label is not generated:

    fun printUntilStop() { 
      val list = listOf("a", "b", "stop", "c") 
      list.forEach { 
        if (it == "stop") return@forEach 
        else println(it) 
      } 
    }
主站蜘蛛池模板: 石首市| 伊宁市| 泰州市| 合肥市| 连江县| 萍乡市| 阳春市| 漯河市| 平和县| 正镶白旗| 临江市| 鹤岗市| 延长县| 基隆市| 奎屯市| 隆子县| 凭祥市| 昌吉市| 莒南县| 志丹县| 安吉县| 收藏| 米易县| 页游| 黔东| 恩平市| 东乌珠穆沁旗| 密山市| 屯昌县| 富蕴县| 绍兴市| 文山县| 英吉沙县| 永修县| 东源县| 石棉县| 林周县| 藁城市| 普格县| 潜山县| 衡山县|