# 基本语法##定义包软件包规范应位于源文件的顶部:
package my.demo
import java.util.*
// ...
不需要匹配目录和包:源文件可以任意放在文件系统中。## 定义功能全Kotlin参考 编辑页面基本语法定义包软件包规范应位于源文件的顶部:package my.demoimport java.util.*// …不需要匹配目录和包:源文件可以任意放在文件系统中。参见包。定义功能具有返回类型的两个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)
}
## 定义局部变量分配一次(只读)局部变量:
fun main(args: Array<String>) {
//sampleStart
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
//sampleEnd
println("a = $a, b = $b, c = $c")
}
可变变量:
fun main(args: Array<String>) {
//sampleStart
var x = 5 // `Int` type is inferred
x += 1
//sampleEnd
println("x = $x")
}
## 注释就像Java和JavaScript一样,Kotlin支持行尾和//注释。
// This is an end-of-line comment
/* This is a block comment
on multiple lines. */
与Java不同,Kotlin中的块注释可以嵌套。## 使用字符串模板
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)
}
## 使用条件表达式
//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)}")
}
## 使用可空值并检查null当空值可能时,引用必须被明确地标记为可空。如果不持有整数则返回nullstr:
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")
}
## 使用类型检查和自动转换这是操作者检查是否一个表达式是一个类型的一个实例。如果为特定类型检查不可变的局部变量或属性,则不需要显式转换:
//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)
}
## 使用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
}
## 使用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
}
##使用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"))
}
##使用范围检查一个数字是使用范围内操作
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
}
## 使用集合迭代集合:
fun main(args: Array<String>) {
val items = listOf("apple", "banana", "kiwi")
//sampleStart
for (item in items) {
println(item)
}
//sampleEnd
}
检查如果集合包含对象使用in{关键词} 操作:
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
}