- Learn Kotlin Programming(Second Edition)
- Stephen Samuel Stefan Bocutiu
- 281字
- 2021-06-24 14:13:30
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) } }
- 多媒體CAI課件設計與制作導論(第二版)
- Mastering Swift 2
- Easy Web Development with WaveMaker
- Learning Data Mining with R
- Mastering openFrameworks:Creative Coding Demystified
- 編程菜鳥學Python數據分析
- 0 bug:C/C++商用工程之道
- Web性能實戰
- Go語言編程
- Python開發基礎
- The Statistics and Calculus with Python Workshop
- Redmine Cookbook
- Yii2 By Example
- 前端Serverless:面向全棧的無服務器架構實戰
- Visual C++網絡編程教程(Visual Studio 2010平臺)