fun main() {
val a = -114
val b = -1919
val max = if (a > b) {
println("$a is larger than $b.")
println("max variable holds value of a.")
a
} else {
println("$b is larger than $a.")
println("max variable holds value of b.")
b
}
println("max = $max")
}
/*
-114 is larger than -1919.
max variable holds value of a.
max = -114
进程已结束,退出代码0
*/
fun main() {
val a = -114
val b = -1919
val max = if (a > b) shutA(a,b) else shutB(a,b)
println("max = $max")
}
fun shutA(a: Int, b: Int): Int {
println("$a is larger than $b.")
println("max variable holds value of a.")
return a
}
fun shutB(a: Int, b: Int): Int {
println("$b is larger than $a.")
println("max variable holds value of b.")
return b
}
fun main() {
val n = -1
when (n) {
1, 2, 3 -> println("n is a positive integer less than 4.")
0 -> println("n is zero")
-1, -2 -> println("n is a negative integer greater than 3.")
}
}
我们还可以配合is关键字和!is来判断是我们选择的对象是否是某个类
fun main() {
val mutableListOf = mutableListOf("String", false, 1, 'c')
mutableListOf.forEach() {
when(it) {
is String -> println("String")
is Boolean -> println("Boolean")
is Char -> println("Char")
else -> println("Int")
}
}
}
fun main() {
println("请输入你的分数")
when(readLine()?.toInt()) {
in 0 until 60 -> println("不及格")
in 60 until 80 -> println("良好")
in 80 .. 100 -> println("优秀")
else -> println("请输入正确的成绩")
}
}
fun main(args: Array<String>) {
first@ for (i in 1..4) {
second@ for (j in 1..2) {
println("i = $i; j = $j")
if (i == 2)
break@first
}
}
}
/*
i = 1; j = 1
i = 1; j = 2
i = 2; j = 1
*/
fun main(args: Array<String>) {
here@ for (i in 1..5) {
for (j in 1..4) {
if (i == 3 || j == 2)
continue@here
println("i = $i; j = $j")
}
}
}
/*
i = 1; j = 1
i = 2; j = 1
i = 4; j = 1
i = 5; j = 1
*/
fun add(a:Int = 114, b:Int = 1919, myMethod : ()->Unit ) :Int {
myMethod()
println("first == $a second == $b")
return a+b
}
fun main() {
val res = add(myMethod = { println("this is test method") })
println(res)
}
/*
this is test method
first == 114 second == 1919
2033
*/