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

Statements versus expressions

Kotlin utilizes expressions more widely than Java, so it is important to know the difference between a statement and an expression. A program is basically a sequence of statements and expressions. An expression produces a value, which can be used as part of another expression, variable assignment, or function parameter. An expression is a sequence of one or more operands (data that is manipulated) and zero or more operators (a token that represents a specific operation) that can be evaluated to a single value:


Let's review some examples of expressions from Kotlin:

Expression (produces a value)

Assigned value

Expression of type

a = true

true

Boolean

a = "foo" + "bar"

"foobar"

String

a = min(2, 3)

2

Integer

a = computePosition().getX()

Value returned by the getX method

Integer

 

Statements, on the other hand, perform an action and cannot be assigned to a variable, because they simply don't have a value. Statements can contain language keywords that are used to define classes (class), interfaces (interface), variables (val, var), functions (fun), loop logic (break, continue) and so on. Expressions can also be treated as a statement when the value returned by the expression is ignored (do not assign a value to the variable, do not return it from a function, do not use it as part of other expressions, and so on).

Kotlin is an expression-oriented language. This means that many constructs that are statements in Java are treated as expressions in Kotlin. The first major difference is the fact that Java and Kotlin have different ways of treating control structures. In Java they are treated as statements, while in Kotlin all control structures are treated as expressions, except for loops. This means that in Kotlin we can write very concise syntax using control structures. We will see examples in upcoming sections.

主站蜘蛛池模板: 新津县| 高碑店市| 永寿县| 嘉禾县| 鹿泉市| 琼海市| 彭泽县| 靖州| 玉溪市| 靖边县| 罗定市| 浙江省| 昭苏县| 德安县| 承德县| 石渠县| 木兰县| 正安县| 平顶山市| 丹棱县| 东海县| 威远县| 右玉县| 通城县| 西丰县| 凤山县| 乐亭县| 福州市| 图们市| 油尖旺区| 郯城县| 怀化市| 米脂县| 基隆市| 秀山| 西乌珠穆沁旗| 永和县| 河西区| 房山区| 巩留县| 绥阳县|