这是 kotlin 学习教程第二篇,为大家讲解 kotlin 的语法。因为本系列文章是作者翻译官方文档而来,所以有一些描述可能不太正确,建议大家都到官网运行一下实例,有助于理解。
data class Customer(val name: String, val email: String)
提供带有下列功能的 Customer 类:
所有属性的getter (和 var 的 setter)
equals()
hashCode()
toString()
copy()
所有属性的 component1(),component2(),…
fun foo(a: Int = 0, b: String = "") { ... }
val positives = list.filter { x -> x > 0 }
或者,可以更简洁一些:
val positives = list.filter { it > 0 }
println("Name $name")
when (x) {
is Foo -> ...
is Bar -> ...
else -> ...
}
for ((k, v) in map) {
println("$k -> $v")
}
k,v 可以调用任意事件
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) { ... }
val list = listOf("a", "b", "c")
val map = mapOf("a" to 1, "b" to 2, "c" to 3)
println(map["key"])
map["key"] = value
val p: String by lazy {
// 计算字符串
}
fun String.spaceToCamelCase() { ... }
"Convert this to camelcase".spaceToCamelCase()
object Resource {
val name = "Name"
}
val files = File("Test").listFiles()
println(files?.size)
val files = File("Test").listFiles()
println(files?.size ?: "empty")
val data = ...
val email = data["email"] ?: throw IllegalStateException("Email is missing!")
val data = ...
data?.let {
... // 如果不为空,执行这一块代码
}
fun transform(color: String): Int {
return when (color) {
"Red" -> 0
"Green" -> 1
"Blue" -> 2
else -> throw IllegalArgumentException("Invalid color param value")
}
}
fun test() {
val result = try {
count()
} catch (e: ArithmeticException) {
throw IllegalStateException(e)
}
// 与 result 一起工作
}
fun foo(param: Int) {
val result = if (param == 1) {
"one"
} else if (param == 2) {
"two"
} else {
"three"
}
}
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")
}
class Turtle {
fun penDown()
fun penUp()
fun turn(degrees: Double)
fun forward(pixels: Double)
}
val myTurtle = Turtle()
with(myTurtle) { //画一个 100 像素的平方
penDown()
for(i in 1..4) {
forward(100.0)
turn(90.0)
}
penUp()
}
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 T: Any> Gson.fromJson(json): T = this.fromJson(json, T::class.java)
val b: Boolean? = ...
if (b == true) {
...
} else {
// `b` 为 false 或者 null
}