从本篇博客开始,将介绍Kotlin官方文档的内容。
本文翻译自Kotlin官方学习文档:https://kotlinlang.org/docs/kotlin-docs.pdf
基础语法
包定义
包声明应该在源文件的顶部
package my.demo
import java.util.*
// ...
并不要求目录和包匹配:源文件可以在文件系统的任何地方
详见Packages
方法定义
具有两个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返回类型可以被省略
fun printSum(a: Int, b: Int) {
println("sum of $a and $b is ${a + b}")
}
详见Functions
定义局部变量
只赋值一次(只读)的局部变量
val a: Int = 1 // 声明变量时赋值
val b = 2 // 推断值为Int类型
val c: Int // 如果没有初始化,必须定义类型
c = 3 // 延期赋值
可变变量
var x = 5 //推断值为Int类型
x += 1
详见Properties And Fields.
注释
像Java和JavaScript一样,Kotlin支持行尾注释和块注释
// 这是一个单行注释
/* 这是一个多行的
块注释 */
和Java不同的是,Kotlin中的块注释可以嵌套。
详见Documenting Kotlin Code获取文档注释语法的信息
字符串模板
fun maxOf(a: Int, b: Int): Int {
if (a > b) {
return a
} else {
return b
}
}
使用表达式
fun maxOf(a: Int, b: Int) = if (a > b)
详见if-expressions.
使用nullable检查空值
如果一个引用可能为空,必须显示标记为可null
如果str没有持有整数值,返回空
fun parseInt(str: String): Int? {
// ...
}
使用方法返回null
fun printProduct(arg1: String, arg2: String) {
val x = parseInt(arg1)
val y = parseInt(arg2)
// x * y将产生错误,因为它们可能为空
if (x != null && y != null) {
// null值检查后,x和y被自动转换为非空值
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
}
// null值检查后,x和y被自动转换为非空值
println(x * y)
详见 Null-safety.
类型检查和自动转换
is操作符用来检查一个实例是否属性一个类型。如果一个不可变变量或属性进行了特定类型检查,就没有必要进行显示的转换
fun getStringLength(obj: Any): Int? {
if (obj is String) {
// obj被自动转换为String类型
return obj.length
}
// 在类型检查代码的外部,obj仍然被当做Any类型
return null
}
或者这样写
fun getStringLength(obj: Any): Int? {
if (obj !is String) return null
// 这里obj被自动转换为String类型
return obj.length
}
甚至可以这样写
fun getStringLength(obj: Any): Int? {
// 在&&右边,obj被自动转换为String类型
if (obj is String && obj.length > 0) {
return obj.length
}
return null
}
详见 Classes and Type casts
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]}")
}
详见for loop
while循环
val items = listOf("apple", "banana", "kiwi")
var index = 0
while (index < items.size) {
println("item at $index is ${items[index]}")
index++
}
详见while loop
when表达式
fun describe(obj: Any): String =
when (obj) {
1 -> "One"
"Hello" -> "Greeting"
is Long -> "Long"
!is String -> "Not a string"
else -> "Unknown"
}
详见when expression
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表达式过滤集合和实现map功能
fruits
.filter { it.startsWith("a") }
.sortedBy { it }
.map { it.toUpperCase() }
.forEach { println(it) }
详见 Higher-order functions and Lambdas.
习惯用语
随机收集的在Kotlin中使用频率较高的习惯用语。如果你有喜欢的习语,可以通过pull request来共享
创建DTOs (POJOs/POCOs)
data class Customer(val name: String, val email: String)
提供了一个Customer类,拥有以下功能:
- 所有属性的getters(变量提供setters)
- equals()
- hashCode()
- toString
- copy()
- 所有属性的component1() , component2() , …(详见 Data classes)
方法默认参数
fun foo(a: Int = 0, b: String = "") { ... }
过滤list
val positives = list.filter { x -> x > 0 }
或者可以更简洁
val positives = list.filter { it > 0 }
字符串内插
println("Name $name")
实例检查
when (x) {
is Foo -> ...
is Bar -> ...
else -> ...
}
遍历map/list对
for ((k, v) in map) {
println("$k -> $v")
}
k、v可以被称作任何事物
Ranges
for (i in 1..100) { ... } // 闭区间:包含100
for (i in 1 until 100) { ... } // 半开区间:不包含100
for (x in 2..10 step 2) { ... }
for (x in 10 downTo 1) { ... }
if (x in 1..10) { ... }
只读list
val list = listOf("a", "b", "c")
只读map
val map = mapOf("a" to 1, "b" to 2, "c" to 3)
访问map
println(map["key"])
map["key"] = value
Lazy属性
val p: String by lazy {
// compute the string
}
扩展函数
fun String.spaceToCamelCase() { ... }
"Convert this to camelcase".spaceToCamelCase()
单例模式
object Resource {
val name = "Name"
}
非空判断简写
val files = File("Test").listFiles()
println(files?.size)
If not null and else简写
val files = File("Test").listFiles()
println(files?.size ?: "empty")
If null语句执行
val data = ...
val email = data["email"] ?: throw IllegalStateException("Email is missing!")
If not null语句执行
val data = ...
data?.let {
... // execute this block if not null
}
If not null,对非空值进行map操作
val data = ...
val mapped = data?.let { transformData(it) } ?: defaultValueIfDataIsNull
when声明返回值
fun transform(color: String): Int {
return when (color) {
"Red" -> 0
"Green" -> 1
"Blue" -> 2
else -> throw IllegalArgumentException("Invalid color param value")
}
}
try/catch表达式
fun test() {
val result = try {
count()
} catch (e: ArithmeticException) {
throw IllegalStateException(e)
}
// 对结果执行操作
}
If表达式
fun foo(param: Int) {
val result = if (param == 1) {
"one"
} else if (param == 2) {
"two"
} else {
"three"
}
}
返回值为Unit的生成器方法
fun arrayOfMinusOnes(size: Int): IntArray {
return IntArray(size).apply { fill(-1) }
}
单个表达式的函数
fun theAnswer() = 42
等同于
fun theAnswer(): Int {
return 42
}
还可以有效地和其他习惯用语结合,简化代码。例如:和when表达式
fun transform(color: String): Int = when (color) {
"Red" -> 0
"Green" -> 1
"Blue" -> 2
else -> throw IllegalArgumentException("Invalid color param value")
}
调用一个对象实例的多个方法(使用with)
class Turtle {
fun penDown()
fun penUp()
fun turn(degrees: Double)
fun forward(pixels: Double)
}
val myTurtle = Turtle()
with(myTurtle) { //draw a 100 pix square
penDown()
for(i in 1..4) {
forward(100.0)
turn(90.0)
}
penUp()
}
Java7的资源使用
val stream = Files.newInputStream(Paths.get("/some/file.txt"))
stream.buffered().reader().use { reader ->
println(reader.readText())
}
需要使用泛型类型的泛型函数简洁形式
// public final class Gson {
// ...
// public <T> T fromJson(JsonElement json, Class<T> classOfT) throws JsonSyntaxException {
// ...
inline fun <reified T: Any> Gson.fromJson(json): T = this.fromJson(json, T::class.java)
消费一个空的布尔值
val b: Boolean? = ...
if (b == true) {
...
} else {
//b为false或空
}
编码约定
本页包含Kotlin语言现在的编码风格
命名风格
如果有怀疑,默认按照Java的编码规范,例如:
名称使用驼峰命名法(避免在名称中使用下划线),首字母要大写
方法和属性名使用小写字母开头
使用4个空格的缩进
public方法应该有文档说明,能在Kotlin文档中显示
冒号
在使用冒号分隔类型和子类型时,在冒号前加一个空格,在冒号分隔实例和类型时不需要加空格
interface Foo<out T : Any> : Bar {
fun foo(a: Int): T
}
Lambda表达式
在lanbda表达式中,空格用在花括号两边、将参数和函数体分开的箭头两侧。如果可能,lambda表达式应该在花括号外传递
list.filter { it > 10 }.map { element -> element * 2 }
在没有简写和嵌套的lambda表达式中,建议使用it代替显式地参数声明。在嵌套且带有参数的lambda表达式中,参数应该被显式地声明
类的头形式
带有几个参数的类可以被写在一行中
class Person(id: Int, name: String)
有很长类头的类应该格式化,使得每个主要的构造方法参数都在带缩进的一行中。关闭的圆括号也应该在一个新的行中。如果使用继承,父类的构造方法或实现的接口列表应该位于圆括号的同一行中
class Person(
id: Int,
name: String,
surname: String
) : Human(id, name) {
// ...
}
如果有多个接口,父类的构造方法应该位于第一行,然后每个接口位于不同的行中
class Person(
id: Int,
name: String,
surname: String
) : Human(id, name),
KotlinMaker {
// ...
}
构造方法的参数可以使用常规缩进或连续缩进(常规缩进的两倍)
Unit
如果一个方法返回Unit类型,返回类型应该被省略
fun foo() { // 省略了": Unit"
}
下一篇:Kotlin基础知识