//sampleStart funsum(a: Int, b: Int): Int { return a + b } //sampleEnd funsum(a: Int, b: Int) = a + b
funmain() { println("sum of 19 and 23 is ${sum(19, 23)}") printSum(-11,53) } funprintSum(a: Int, b: Int): Unit { println("sum of $a and $b is ${a + b}") }
变量
如果有赋值,那么它可以自动推出变量类型,否则需要声明变量类型 val 只读变量,不可以修改 var 可读可改变量 const val 常量,必须定义在函数之外。
1 2 3 4
val a: Int = 1// 立即赋值 val b = 2// 自动推断出 `Int` 类型 val c: Int// 如果没有初始值类型不能省略 c = 3// 明确赋值
var m = if (a > b) a else b <=> m = a>b ? a :b 三元表达式
for循环
1 2 3 4 5 6 7 8 9 10 11 12 13
sampleStart var items = listOf("apple","banana","xigua") for (item in items){ println(item) }
//sampleEnd //indices表示index //indeces 表示的是一个集合类型,包括从(0...list.size-1) //${items[index]} = ${items[item]} for (index in items.indices) { println("item at $index is ${items[index]}") }
while循环
1 2 3 4 5
var index = 0 while (index < items.size){ println("item in $index is ${items[index]}") index++ }
//使用 in 操作符来检测某个数字是否在指定区间内 val x = 10 val y = 9 if(x in1..y+1){ println("fits in range") } //最后可以正确输出结果
//检测某个数字是否在指定区间外。 val list = listOf("a", "b", "c")
if (-1 !in0..list.lastIndex) { println("-1 is out of range") } if (list.size !in list.indices) { println("list size is out of valid list indices range, too") }
funmain() { funprintLength(obj: Any) { println("Getting the length of '$obj'. Result: ${getStringLength(obj) ?: "Error: The object is not a string"} ") } printLength("Incomprehensibilities") printLength(1000) printLength(listOf(Any())) }