简介
class Foo {
val b: String = "b" // val变量不可变
var i: Int = 0 // var变量可变
fun hello() {
val str = "Hello"
print("$str World")
}
fun sum(x: Int, y: Int): Int {
return x + y
}
fun maxOf(a: Float, b: Float) = if (a > b) a else b
}
val x = 4
val y = 7
print("sum of $x and $y is ${x + y}") // sum of 4 and 7 is 11
val a = "abc" // String类型
val b = 4 // Int类型
val c: Double = 0.7 // 显示声明类型
val d: List<String> = ArrayList() // 显示声明类型
if (obj is String) {
print(obj.toUpperCase()) // obj被识别为String类型
}
val john1 = Person("John")
val john2 = Person("John")
john1 == john2 // true (结构相等)
john1 === john2 // false (对象/引用不相等)
for (i in 1..100) { ... }
for (i in 0 until 100) { ... }
for (i in 2..10 step 2) { ... }
for (i in 10 downTo 1) { ... }
if (x in 1..10) { ... }
fun build(title: String, width: Int = 800, height: Int = 600) {
Frame(title, width, height)
}
when(x){
1 -> print("x is 1")
2 -> print("x is 2")
3, 4 -> print("x is 3 or 4")
in 5..10 -> print("x is 5, 6, 7, 8, 9, or 10")
else -> print("x is out of range")
}
val res: Boolean = when {
obj == null -> false
obj is String -> true
else -> throw IllegalStateException()
}
作者:王炜鑫:原文地址