原文地址
Defining packages
包的声明应该在源文件的顶端
<code>package my.demo
import java.util. * // ...
目录和包不要求匹配
Defining functions
函数有两个整形参数和返回整形结果
fun sum(a: Int, b: Int): Int {
return a + b
}
函数根据表达式内容推出返回结果
<pre><code>fun sum(a: Int, b: Int) = a + b</pre></code>
函数无返回值
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}")
}
Defining local variables
定义常量
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
可变变量
var x = 5 // `Int` type is inferred
x += 1
Comments
就像Java和JavaScript,Kotlin 支持行尾和块注释
// This is an end-of-line comment
/* This is a block comment on multiple lines. */
和Java不同的是,Kotlin块注释能够被嵌套
Using string templates
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"
Using conditional expressions
fun maxOf(a: Int, b: Int): Int {
if (a > b) {
return a
} else {
return b
}
}
Using if as an expression:
fun maxOf(a: Int, b: Int) = if (a > b) a else b
Using nullable values and checking for null
引用的值如果可能为空的话那么必须被明确的标注为可空的。
返回空如果str不可被转化为整数
fun parseInt(str: String): Int? { // ... }
用一个函数返回可空的值
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)
Using type checks and automatic casts
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
}
Using a for loop
val items = listOf("apple", "banana", "kiwi")
for (item in items) {
println(item)
}
或者
val items = listOf("apple", "banana", "kiwi")
for (index in items.indices) {
println("item at $index is ${items[index]}")
}
Using a while loop
val items = listOf("apple", "banana", "kiwi")
var index = 0
while (index < items.size) {
println("item at $index is ${items[index]}")
index++
}
Using when expression
fun describe(obj: Any): String =
when (obj) {
1 -> "One"
"Hello" -> "Greeting"
is Long -> "Long"
!is String -> "Not a string"
else -> "Unknown"
}
Using ranges
检查数字在某个范围内用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)
}
for (x in 9 downTo 0 step 3) {
print(x)
}
Using collections
遍历一个集合
for (item in items) {
println(item)
}
检查集合是否包含某个对象用in操作符
when {
"orange" in items -> println("juicy")
"apple" in items -> println("apple is fine too")
}
使用lambda表达式去过滤和转换集合
fruits
.filter { it.startsWith("a") }
.sortedBy { it }
.map { it.toUpperCase() }
.forEach { println(it) }
网友评论