譯自Kotlin Basic Syntax
定義包
軟件包定義(Package specification)應(yīng)位于源文件的頂部:
package my.demo
import java.util.*
// ...
不需要匹配目錄和包:源文件可以任意放在文件系統(tǒng)中声诸。
參見包(Packages) 眉菱。
定義函數(shù)
具有Int
返回類型的兩個Int
參數(shù)的函數(shù):
fun sum(a: Int, b: Int): Int {
return a + b
}
fun main(args: Array<String>) {
print("sum of 3 and 5 is ")
println(sum(3, 5))
}
具有表達(dá)體(expression body)和推斷返回類型(inferred return type)的函數(shù):
fun sum(a: Int, b: Int) = a + b
fun main(args: Array<String>) {
println("sum of 19 and 23 is ${sum(19, 23)}")
}
返回?zé)o意義值的函數(shù):
fun printSum(a: Int, b: Int): Unit {
println("sum of $a and $b is ${a + b}")
}
fun main(args: Array<String>) {
printSum(-1, 8)
}
Unit
返回類型可以省略:
fun printSum(a: Int, b: Int) {
println("sum of $a and $b is ${a + b}")
}
fun main(args: Array<String>) {
printSum(-1, 8)
}
請參閱函數(shù)(Functions) 试幽。
定義局部變量
賦值一次(只讀)(Assign-once (read-only))局部變量:
fun main(args: Array<String>) {
val a: Int = 1 // immediate assignment
val b = 2 // `Int` type is inferred
val c: Int // Type required when no initializer is provided
c = 3 // deferred assignment
println("a = $a, b = $b, c = $c")
}
可變(Mutable)變量:
fun main(args: Array<String>) {
var x = 5 // `Int` type is inferred
x += 1
println("x = $x")
}
另請參見屬性和字段 (Properties And Fields)。
注釋
就像Java和JavaScript一樣影所,Kotlin支持行尾和塊注釋赠制。
// This is an end-of-line comment
/* This is a block comment
on multiple lines. */
與Java不同边酒,Kotlin中的塊注釋可以嵌套经柴。
有關(guān)文檔注釋語法的信息,請參閱注釋Kotlin代碼 (Documenting Kotlin Code )墩朦。
使用字符串模板
fun main(args: Array<String>) {
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"
println(s2)
}
請參閱String模板 (String templates)坯认。
使用條件表達(dá)式
fun maxOf(a: Int, b: Int): Int {
if (a > b) {
return a
} else {
return b
}
}
fun main(args: Array<String>) {
println("max of 0 and 42 is ${maxOf(0, 42)}")
}
使用if
表達(dá)式:
fun maxOf(a: Int, b: Int) = if (a > b) a else b
fun main(args: Array<String>) {
println("max of 0 and 42 is ${maxOf(0, 42)}")
}
使用可空值(nullable values)并檢查null
當(dāng)空值可能時氓涣,引用必須被明確地標(biāo)記為可空(explicitly marked as nullable when null value is possible) 牛哺。
如果str不包含整數(shù),則返回null :
fun parseInt(str: String): Int? {
// ...
}
使用返回可空值的函數(shù):
fun parseInt(str: String): Int? {
return str.toIntOrNull()
}
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")
}
}
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)
// ...
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)
}
fun main(args: Array<String>) {
printProduct("6", "7")
printProduct("a", "7")
printProduct("99", "b")
}
見空安全(Null-safety) 劳吠。
使用類型檢查和自動轉(zhuǎn)換
is
運(yùn)算符檢查表達(dá)式是否是類型的實(shí)例引润。 如果檢查不可變(immutable)局部變量或?qū)傩詾樘囟愋停瑒t不需要顯式轉(zhuǎn)換:
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 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()))
}
或者
fun getStringLength(obj: Any): Int? {
if (obj !is String) return null
// `obj` is automatically cast to `String` in this branch
return obj.length
}
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()))
}
甚至
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
}
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)和類型轉(zhuǎn)換 (Type casts)痒玩。
使用for循環(huán)
fun main(args: Array<String>) {
val items = listOf("apple", "banana", "kiwi")
for (item in items) {
println(item)
}
}
要么
fun main(args: Array<String>) {
val items = listOf("apple", "banana", "kiwi")
for (index in items.indices) {
println("item at $index is ${items[index]}")
}
}
參見for循環(huán)(for loop) 淳附。
使用while循環(huán)
fun main(args: Array<String>) {
val items = listOf("apple", "banana", "kiwi")
var index = 0
while (index < items.size) {
println("item at $index is ${items[index]}")
index++
}
}
看到while循環(huán) (while loop)。
表達(dá)when使用
fun describe(obj: Any): String =
when (obj) {
1 -> "One"
"Hello" -> "Greeting"
is Long -> "Long"
!is String -> "Not a string"
else -> "Unknown"
}
fun main(args: Array<String>) {
println(describe(1))
println(describe("Hello"))
println(describe(1000L))
println(describe(2))
println(describe("other"))
}
看when表達(dá)式(when expression)凰荚。
使用范圍
使用in
操作符檢查數(shù)字是否在范圍內(nèi):
fun main(args: Array<String>) {
val x = 10
val y = 9
if (x in 1..y+1) {
println("fits in range")
}
}
檢查一個數(shù)字是否超出范圍:
fun main(args: Array<String>) {
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")
}
}
在一個范圍內(nèi)迭代:
fun main(args: Array<String>) {
for (x in 1..5) {
print(x)
}
}
或過程(progression):
fun main(args: Array<String>) {
for (x in 1..10 step 2) {
print(x)
}
for (x in 9 downTo 0 step 3) {
print(x)
}
}
見范圍(Ranges) 燃观。
使用集合
在一個集合內(nèi)迭代:
fun main(args: Array<String>) {
val items = listOf("apple", "banana", "kiwi")
for (item in items) {
println(item)
}
}
使用in
運(yùn)算符檢查集合是否包含一個對象:
fun main(args: Array<String>) {
val items = setOf("apple", "banana", "kiwi")
when {
"orange" in items -> println("juicy")
"apple" in items -> println("apple is fine too")
}
}
使用lambda表達(dá)式過濾和映射集合(filter and map collections):
fun main(args: Array<String>) {
val fruits = listOf("banana", "avocado", "apple", "kiwi")
fruits
.filter { it.startsWith("a") }
.sortedBy { it }
.map { it.toUpperCase() }
.forEach { println(it) }
}
請參閱高階函數(shù)和Lambdas(Higher-order functions and Lambdas) 。