第一章 基本语法
定义包
包名应该在源文件的最上面定义
package my.demo
import java.util.*
包名不需要匹配文件路径,源文件可以放在任意路径下。
定义方法
含有两个Int
型参数和Int
返回值的方法定义如下:
fun sum(a: Int, b: Int): Int {
return a + b
}
方法可以用表达式的形式定义,返回值类型根据参数类型判断:
fun sum(a: Int, b: Int) = a + b
没有返回值的方法定义:
fun printSum(a: Int, b: Int): Unit {
println("sum of $a and $b is ${a + b}")
}
Unit
可以省略。
定义本地变量
只能赋值一次(只读)本地变量(JAVA中的final型?):
val a: Int = 1 // 立即赋值
val b = 2 // `Int` 类型是根据赋值的类型确定的
val c: Int // 变量如果没有赋初值,必须定义类型
c = 3 // 推迟赋值(3、4行是同一个变量)
可变的变量:
var x = 5 // `Int` type is inferred
x += 1
注释
与大部分语言一样,支持//和/* */两种注释方法。不同的是Kotlin的/* */可以内嵌
使用字符模板
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"
使用条件表达式
fun maxOf(a: Int, b: Int): Int {
if (a > b) {
return a
} else {
return b
}
}
或者将方法赋值为表达式:
fun maxOf(a: Int, b: Int) = if (a > b) a else b
null值的使用与检测
如果一个引用的值有可能是null,该引用必须显式的标记为nullable。
如下:如果str
不包含数字,则会返回null:
fun parseInt(str: String): Int? {
// ...
}
null值的检测:
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")
}
}
类型检测和自动转型
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
}
for循环
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]}")
}
while循环
val items = listOf("apple", "banana", "kiwi")
var index = 0
while (index < items.size) {
println("item at $index is ${items[index]}")
index++
}
when表达式
fun describe(obj: Any): String =
when (obj) {
1 -> "One"
"Hello" -> "Greeting"
is Long -> "Long"
!is String -> "Not a string"
else -> "Unknown"
}
(PS:有点像switch语句,但是功能更加强大)
区间(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)
}
集合
集合的迭代
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) }
呵呵
翻译了半天,发现原来gitBook上早有了全本的翻译,提供个地址,大家自己去下载吧(笑哭脸)。
项目地址.