常量 val a: Int = 5
变量 var a: Int = 5
Any:匹配任何类型
?:nullable,比如 a?.toString,如果 a 为 null 不会出错。
函数基本结构
fun copyAddress(address: Address): Address {
val result = Address() // there's no 'new' keyword in Kotlin
result.name = address.name // accessors are called
result.street = address.street
// ...
return result
}
1. 函数名,参数,返回类型
fun sum(a: Int, b: Int): Int {
return a + b
}
2. 函数名,参数,返回值
fun sum(a: Int, b: Int) = a + b
3. 函数名,参数,无返回值
fun printSum(a: Int, b: Int) {
print(a + b)
}
无返回值可以用 Unit 表示
String 字符串中可以加参数
print("First argument: ${array[0]}")
if
val max = if (a > b) {
print("Choose a")
a
}
else {
print("Choose b")
b
}
fun max(a: Int, b: Int) = if (a > b) a else b
when (switch in Java)
when (x) {
1 -> print("x == 1")
2 -> print("x == 2")
else -> { // Note the block
print("x is neither 1 nor 2")
}
}
类型转换 (cast)
fun getStringLength(obj: Any): Int? {
if (obj is String) {
// `obj` is automatically cast to `String` in this branch
return obj.length
}
// `obj` is still of type `Any` outside of the type-checked branch
return null
}