- Learn Kotlin Programming(Second Edition)
- Stephen Samuel Stefan Bocutiu
- 363字
- 2021-06-24 14:13:29
Control flow as expressions
An expression is a statement that evaluates to a value. The following expression evaluates to true:
"hello".startsWith("h")
A statement, on the other hand, has no resulting value returned. The following is a statement because it assigns a value to a variable, but does not evaluate to anything itself:
val a = 1
In Java, the common control flow blocks, such as if...else and try..catch, are statements. They do not evaluate to a value, so it is common in Java, when using these, to assign the results to a variable initialized outside the block:
public boolean isZero(int x) { boolean isZero; if (x == 0) isZero = true; else isZero = false; return isZero; }
In Kotlin, the if...else and try..catch control flow blocks are expressions. This means the result can be directly assigned to a value, returned from a function, or passed as an argument to another function.
This small, yet powerful, feature allows boilerplate code to be reduced, code made more readable, and the use of mutable variables avoided. The typical use case of declaring a variable outside of an if statement to then initialize it inside either branch can be avoided completely:
val date = Date() val today = if (date.year == 2016) true else false fun isZero(x: Int): Boolean { return if (x == 0) true else false }
A similar technique can be used for the try..catch blocks, as follows:
val success = try { readFile() true } catch (e: IOException) { false }
In the preceding example, the success variable will contain the result of the try block only if it completes successfully; otherwise, the catch clause return value will be used, in this case, false.
Expressions need not be single lines. They can be blocks, and in those cases, the last line must be an expression, and that expression is the value that the block evaluates to.
- Mastering ServiceStack
- Ceph Cookbook
- Mastering Selenium WebDriver
- Django開發(fā)從入門到實(shí)踐
- Visual C++實(shí)例精通
- C語(yǔ)言程序設(shè)計(jì)實(shí)踐教程
- C++程序設(shè)計(jì)基礎(chǔ)教程
- 快人一步:系統(tǒng)性能提高之道
- Windows Phone 7.5:Building Location-aware Applications
- Create React App 2 Quick Start Guide
- 實(shí)戰(zhàn)Java高并發(fā)程序設(shè)計(jì)(第2版)
- PowerDesigner 16 從入門到精通
- The Statistics and Calculus with Python Workshop
- Node.js 6.x Blueprints
- Lync Server Cookbook