Kotlin教程:表达式、语句和块

2020-04-1911:57:59编程语言入门到精通Comments1,710 views字数 834阅读模式

表达式由变量,运算符等组成,它的值是单个值。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/18247.html

下面来看一个例子 -文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/18247.html

val score: Int
score = 90 + 25
Kotlin

这里,90 + 25是一个返回Int值的表达式。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/18247.html

在Kotlin中,if是一个不同于Java的表达式(在Java中,if是一个声明)。 例如,文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/18247.html

fun main(args: Array<String>) {

    val a = 12
    val b = 13
    val max: Int

    max = if (a > b) a else b
    println("$max")
}
Kotlin

这里,if(a > b) a else b是表达式。 然后在上面的程序中将表达式的值赋给max变量。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/18247.html

Kotlin语句

语句是构成完整执行单元的所有内容。 例如,文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/18247.html

val score = 90 + 25
Kotlin

这里,90 + 25是返回115的表达式,val score= 9 * 5;是一个语句。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/18247.html

表达式是语句的一部分。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/18247.html

一些例子:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/18247.html

println("Howdy")
Kotlin
var a = 5
++a
Kotlin
max = if (a > b) a else b
Kotlin

Kotlin块

块是一组括在括号{}中的语句(零个或多个)。 例如,文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/18247.html

fun main(args: Array<String>) {  // main函数块
    val flag = true

    if (flag == true) {      // if块的开始
        print("Hey ")
        print("jude!")
    }                        // if块的结束
}                            // main函数块的结束
Kotlin

if是分支块,则有两个语句:print("Hey ")print(" jude!")文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/18247.html

print("Hey ")
print("jude!")
Kotlin

同样,main()函数也有一个块主体。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/18247.html

val flag = true

if (flag == true) {      // 块开始
    print("Hey ")
    print("jude!")
}                        // 块结果

//原文出自【易百教程】,商业转载请联系作者获得授权,非商业转载请保留原文链接:https://www.yiibai.com/kotlin/statement-expression.html文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/18247.html

文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/18247.html
  • 本站内容整理自互联网,仅提供信息存储空间服务,以方便学习之用。如对文章、图片、字体等版权有疑问,请在下方留言,管理员看到后,将第一时间进行处理。
  • 转载请务必保留本文链接:https://www.cainiaoxueyuan.com/ymba/18247.html

Comment

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定