帶你快速入門,讀懂Kotlin基本語法~
基本語法
定義包
包應(yīng)該在源文件的頭部聲明:
package my.demo
import java.util.*
// ...
不需要匹配目錄和包:源文件可以任意放在文件系統(tǒng)中般妙。
查看 Packages.
定義函數(shù)
有兩個 Int
參數(shù) 和 Int
返回值的函數(shù)定義:
//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))
}
表達(dá)式作為函數(shù)體化戳,返回類型為推斷所得的函數(shù):
//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)}")
}
返回?zé)o意義值的函數(shù):
//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 // 沒有初始化時(shí)需要指明類型
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 有關(guān)文檔注釋語法的信息音比。
使用 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 作為表達(dá)式:
//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
當(dāng)空值可能時(shí)唯鸭,引用必須被明確地標(biāo)記為可空。
如果str不包含整數(shù)硅确,則返回null :
fun parseInt(str: String): Int? {
// ...
}
使用返回可空值的函數(shù):
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.
使用類型檢查和自動轉(zhuǎn)換
is 運(yùn)算符檢查表達(dá)式是否是類型的實(shí)例。如果為特定類型檢查不可變的局部變量或?qū)傩悦靼梗瑒t不需要顯式轉(zhuǎn)換:
//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
循環(huán)
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
循環(huán)
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
表達(dá)式
//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.
使用范圍
使用操作符檢查數(shù)字是否在范圍內(nèi):
fun main(args: Array<String>) {
//sampleStart
val x = 10
val y = 9
if (x in 1..y+1) {
println("fits in range")
}
//sampleEnd
}
檢查數(shù)字是否超出范圍:
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
}
使用運(yùn)算符 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表達(dá)式過濾和映射集合:
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
}