带你快速入门,读懂Kotlin基本语法~
基本语法
定义包
包应该在源文件的头部声明:
package my.demo
import java.util.*
// ...
不需要匹配目录和包:源文件可以任意放在文件系统中。
查看 Packages.
定义函数
有两个 Int
参数 和 Int
返回值的函数定义:
//sampleStart
fun sum(a: Int, b: Int): Int {
return a + b
}
//sampleEnd
fun main(args: Array<String>) {
print("sum of 3 and 5 is ")
println(sum(3, 5))
}
表达式作为函数体,返回类型为推断所得的函数:
//sampleStart
fun sum(a: Int, b: Int) = a + b
//sampleEnd
fun main(args: Array<String>) {
println("sum of 19 and 23 is ${sum(19, 23)}")
}
返回无意义值的函数:
//sampleStart
fun printSum(a: Int, b: Int): Unit {
println("sum of $a and $b is ${a + b}")
}
//sampleEnd
fun main(args: Array<String>) {
printSum(-1, 8)
}
Unit
返回类型可以被忽略不写 :
//sampleStart
fun printSum(a: Int, b: Int) {
println("sum of $a and $b is ${a + b}")
}
//sampleEnd
fun main(args: Array<String>) {
printSum(-1, 8)
}
查看 Functions.
定义局部变量
一次分配(只读)的局部变量:
fun main(args: Array<String>) {
//sampleStart
val a: Int = 1 // 立即赋值
val b = 2 // `Int` 类型是推断得出ed
val c: Int // 没有初始化时需要指明类型
c = 3 // 之后赋值
//sampleEnd
println("a = $a, b = $b, c = $c")
}
可变变量:
fun main(args: Array<String>) {
//sampleStart
var x = 5 // `Int` 类型是推断的
x += 1
//sampleEnd
println("x = $x")
}
注释
和 Java 与 JavaScript 类似,Kotlin 支持 行注释 和 块注释。
// 这是行注释
/* 块
注释
*/
不同于Java,Kotlin 中 块注释可以嵌套。
查看 Documenting Kotlin Code 有关文档注释语法的信息。
使用 String 模板
fun main(args: Array<String>) {
//sampleStart
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"
//sampleEnd
println(s2)
}
查看 String templates.
使用条件语句
//sampleStart
fun maxOf(a: Int, b: Int): Int {
if (a > b) {
return a
} else {
return b
}
}
//sampleEnd
fun main(args: Array<String>) {
println("max of 0 and 42 is ${maxOf(0, 42)}")
}
使用 if 作为表达式:
//sampleStart
fun maxOf(a: Int, b: Int) = if (a > b) a else b
//sampleEnd
fun main(args: Array<String>) {
println("max of 0 and 42 is ${maxOf(0, 42)}")
}
查看 if-expressions.
使用 nullable 值 并且检查 null
当空值可能时,引用必须被明确地标记为可空。
如果str不包含整数,则返回null :
fun parseInt(str: String): Int? {
// ...
}
使用返回可空值的函数:
fun parseInt(str: String): Int? {
return str.toIntOrNull()
}
//sampleStart
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")
}
}
//sampleEnd
fun main(args: Array<String>) {
printProduct("6", "7")
printProduct("a", "7")
printProduct("a", "b")
}
或者
fun parseInt(str: String): Int? {
return str.toIntOrNull()
}
fun printProduct(arg1: String, arg2: String) {
val x = parseInt(arg1)
val y = parseInt(arg2)
//sampleStart
// ...
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)
//sampleEnd
}
fun main(args: Array<String>) {
printProduct("6", "7")
printProduct("a", "7")
printProduct("99", "b")
}
查看 Null-safety.
使用类型检查和自动转换
is 运算符检查表达式是否是类型的实例。如果为特定类型检查不可变的局部变量或属性,则不需要显式转换:
//sampleStart
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
}
//sampleEnd
fun main(args: Array<String>) {
fun printLength(obj: Any) {
println("'$obj' string length is ${getStringLength(obj) ?: "... err, not a string"} ")
}
printLength("Incomprehensibilities")
printLength(1000)
printLength(listOf(Any()))
}
或者
//sampleStart
fun getStringLength(obj: Any): Int? {
if (obj !is String) return null
// `obj` is automatically cast to `String` in this branch
return obj.length
}
//sampleEnd
fun main(args: Array<String>) {
fun printLength(obj: Any) {
println("'$obj' string length is ${getStringLength(obj) ?: "... err, not a string"} ")
}
printLength("Incomprehensibilities")
printLength(1000)
printLength(listOf(Any()))
}
甚或
//sampleStart
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
}
//sampleEnd
fun main(args: Array<String>) {
fun printLength(obj: Any) {
println("'$obj' string length is ${getStringLength(obj) ?: "... err, is empty or not a string at all"} ")
}
printLength("Incomprehensibilities")
printLength("")
printLength(1000)
}
查看 Classes 和 Type casts.
使用 for
循环
fun main(args: Array<String>) {
//sampleStart
val items = listOf("apple", "banana", "kiwi")
for (item in items) {
println(item)
}
//sampleEnd
}
或者
fun main(args: Array<String>) {
//sampleStart
val items = listOf("apple", "banana", "kiwi")
for (index in items.indices) {
println("item at $index is ${items[index]}")
}
//sampleEnd
}
查看 for loop.
使用 while
循环
fun main(args: Array<String>) {
//sampleStart
val items = listOf("apple", "banana", "kiwi")
var index = 0
while (index < items.size) {
println("item at $index is ${items[index]}")
index++
}
//sampleEnd
}
查看 while loop.
使用 when
表达式
//sampleStart
fun describe(obj: Any): String =
when (obj) {
1 -> "One"
"Hello" -> "Greeting"
is Long -> "Long"
!is String -> "Not a string"
else -> "Unknown"
}
//sampleEnd
fun main(args: Array<String>) {
println(describe(1))
println(describe("Hello"))
println(describe(1000L))
println(describe(2))
println(describe("other"))
}
查看 when expression.
使用范围
使用操作符检查数字是否在范围内:
fun main(args: Array<String>) {
//sampleStart
val x = 10
val y = 9
if (x in 1..y+1) {
println("fits in range")
}
//sampleEnd
}
检查数字是否超出范围:
fun main(args: Array<String>) {
//sampleStart
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")
}
//sampleEnd
}
迭代范围:
fun main(args: Array<String>) {
//sampleStart
for (x in 1..5) {
print(x)
}
//sampleEnd
}
或过程:
fun main(args: Array<String>) {
//sampleStart
for (x in 1..10 step 2) {
print(x)
}
for (x in 9 downTo 0 step 3) {
print(x)
}
//sampleEnd
}
查看 Ranges.
使用集合
迭代集合:
fun main(args: Array<String>) {
val items = listOf("apple", "banana", "kiwi")
//sampleStart
for (item in items) {
println(item)
}
//sampleEnd
}
使用运算符 is
检查集合是否包含对象:
fun main(args: Array<String>) {
val items = setOf("apple", "banana", "kiwi")
//sampleStart
when {
"orange" in items -> println("juicy")
"apple" in items -> println("apple is fine too")
}
//sampleEnd
}
使用lambda表达式过滤和映射集合:
fun main(args: Array<String>) {
val fruits = listOf("banana", "avocado", "apple", "kiwi")
//sampleStart
fruits
.filter { it.startsWith("a") }
.sortedBy { it }
.map { it.toUpperCase() }
.forEach { println(it) }
//sampleEnd
}