入门-基础语法
Kotlin官网:Getting Started-Basic Syntax
包定义
必须在源文件的最上端。
package my.demo
import java.util.*
// ...
不要求包定义和文件路径相同,源文件可以放在任意位置。
详见包
方法定义
一个有两个Int型参数,返回值为Int的函数:
fun sum(a: Int, b: Int): Int {
return a + b
}
方法体是一个表达式,返回值类型由返回值自动推断:
fun sum(a: Int, b: Int) = a + b
无返回值函数
fun printSum(a: Int, b: Int): Unit {
println("sum of $a and $b is ${a + b}")
}
返回值类型Unit可以省略
fun printSum(a: Int, b: Int) {
println("sum of $a and $b is ${a + b}")
}
详见函数
变量定义
只读局部变量由关键字val
定义。只能赋值一次。
val a: Int = 1 // 立刻赋值
val b = 2 // `Int`类型由编译器推断
val c: Int // 如果不是立刻赋值则必须声明类型
c = 3 // 推迟赋值
可以多次赋值的变量由关键字var
定义:
var x = 5 // `Int`类型可推断
x += 1
顶级变量
val PI = 3.14
var x = 0
fun incrementX() {
x += 1
}
详见属性和成员
注释
和Java, JavaScript相同,支持单行和多行注释
// 这是单行注释
/* 这是一块
多行注释 */
和Java不同的是多行注释块可以嵌套。
字符串模板
var a = 1
// simple name in template:
val s1 = "a is $a"
a = 2
// arbitrary expression in template:
val s2 = "${s1.replace("is", "was")}, but now is $a"
详见字符串模版
条件表达式
if else else if写法和Java相同
fun maxOf(a: Int, b: Int): Int {
if (a > b) {
return a
} else {
return b
}
}
if作为表达式:
fun maxOf(a: Int, b: Int) = if (a > b) a else b
详见if表达式
可null变量和null检查
当变量可能为null时必须显式声明。
当str不是数字时返回null:
fun parseInt(str: String): Int? {
// ...
}
使用返回值为可null类型的函数:
fun printProduct(arg1: String, arg2: String) {
val x = parseInt(arg1)
val y = parseInt(arg2)
// Using `x * y` yields error because they may hold nulls.
if (x != null && y != null) {
// x and y are automatically cast to non-nullable after null check
println(x * y)
}
else {
println("either '$arg1' or '$arg2' is not a number")
}
}
或:
// ...
if (x == null) {
println("Wrong number format in arg1: '$arg1'")
return
}
if (y == null) {
println("Wrong number format in arg2: '$arg2'")
return
}
// x and y are automatically cast to non-nullable after null check
println(x * y)
详见空安全
类型检查和自动类型转换
使用is
操作符表达式类型是否匹配。如果是不可变量,检查为某一类型后,之后使用不需要再显示的声明转换:
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
}
或:
fun getStringLength(obj: Any): Int? {
if (obj !is String) return null
// `obj` is automatically cast to `String` in this branch
return obj.length
}
也可以:
fun getStringLength(obj: Any): Int? {
// `obj` is automatically cast to `String` on the right-hand side of `&&`
if (obj is String && obj.length > 0) {
return obj.length
}
return null
}
for循环
val items = listOf("apple", "banana", "kiwifruit")
for (item in items) {
println(item)
}
或:
val items = listOf("apple", "banana", "kiwifruit")
for (index in items.indices) {
println("item at $index is ${items[index]}")
}
详见for循环
while循环
val items = listOf("apple", "banana", "kiwifruit")
var index = 0
while (index < items.size) {
println("item at $index is ${items[index]}")
index++
}
详见while循环
when表达式
fun describe(obj: Any): String =
when (obj) {
1 -> "One"
"Hello" -> "Greeting"
is Long -> "Long"
!is String -> "Not a string"
else -> "Unknown"
}
详见when表达式
区间
使用in
操作符判断某个数是否再区间内:
val x = 10
val y = 9
if (x in 1..y+1) {
println("fits in range")
}
判断某个数在区间外:
val list = listOf("a", "b", "c")
if (-1 !in 0..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")
}
遍历某个区间:
for (x in 1..5) {
print(x)
}
遍历某个序列:
for (x in 1..10 step 2) {
print(x)
}
println()
for (x in 9 downTo 0 step 3) {
print(x)
}
详见区间
集合
迭代某个集合:
for (item in items) {
println(item)
}
使用in
操作符判断集合是否包含元素:
when {
"orange" in items -> println("juicy")
"apple" in items -> println("apple is fine too")
}
使用lambda表达式过滤和映射集合:
val fruits = listOf("banana", "avocado", "apple", "kiwifruit")
fruits
.filter { it.startsWith("a") }
.sortedBy { it }
.map { it.toUpperCase() }
.forEach { println(it) }
创建类实例
Kotlin没有new关键之,创建类的对象直接使用val a = 类名(参数)
val rectangle = Rectangle(5.0, 2.0) //no 'new' keyword required
val triangle = Triangle(3.0, 4.0, 5.0)