# 代碼范例
這里列出一些 Kotlin 中會經常用到的代碼。如果你也有,可以通過在 [Github](https://github.com/JetBrains/kotlin-web-site) 上 pull 的方式分享出來。
### 創建 DTO (POJO/POCO)
``` kotlin
data class Customer(val name: String, val email: String)
```
提供了具有下列功能的 `Customer` 類:
* 所有屬性的 getter (使用 `var` 的話也會有 setter)
* `equals()`
* `hashCode()`
* `toString()`
* `copy()`
* 所有屬性的 `component1()`, `component2()`, ... ( [數據類](data-classes.html))
### 函數參數的默認值
``` kotlin
fun foo(a: Int = 0, b: String = "") { ... }
```
### 過濾 list
``` kotlin
val positives = list.filter { x -> x > 0 }
```
或者可以更精煉一點:
``` kotlin
val positives = list.filter { it > 0 }
```
### 字符串插入
``` kotlin
println("Name $name")
```
### 實例檢查
``` kotlin
when (x) {
is Foo -> ...
is Bar -> ...
else -> ...
}
```
### 遍歷 map/list
``` kotlin
for ((k, v) in map) {
println("$k -> $v")
}
```
`k`、 `v` 可以是任何類型
### 使用范圍
``` kotlin
for (i in 1..100) { ... }
for (x in 2..10) { ... }
```
### 只讀的 list
``` kotlin
val list = listOf("a", "b", "c")
```
### 只讀的 map
``` kotlin
val map = mapOf("a" to 1, "b" to 2, "c" to 3)
```
### 訪問 map
``` kotlin
println(map["key"])
map["key"] = value
```
### 延遲屬性
``` kotlin
val p: String by lazy {
// 操作這個 String
}
```
### 擴展函數
``` kotlin
fun String.spaceToCamelCase() { ... }
"Convert this to camelcase".spaceToCamelCase()
```
### 創建單例
``` kotlin
object Resource {
val name = "Name"
}
```
### If not null 簡寫
``` kotlin
val files = File("Test").listFiles()
println(files?.size)
```
### If not null 和 else 簡寫
``` kotlin
val files = File("Test").listFiles()
println(files?.size ?: "empty")
```
### if null 則執行某個指令
``` kotlin
val data = ...
val email = data["email"] ?: throw IllegalStateException("Email is missing!")
```
### if not null 則執行
``` kotlin
val data = ...
data?.let {
... // if not null 則執行這個塊
}
```
### 返回 when 指令
``` kotlin
fun transform(color: String): Int {
return when (color) {
"Red" -> 0
"Green" -> 1
"Blue" -> 2
else -> throw IllegalArgumentException("Invalid color param value")
}
}
```
### 'try/catch' 表達式
``` kotlin
fun test() {
val result = try {
count()
} catch (e: ArithmeticException) {
throw IllegalStateException(e)
}
// Working with result
}
```
### 'if' 表達式
``` kotlin
fun foo(param: Int) {
val result = if (param == 1) {
"one"
} else if (param == 2) {
"two"
} else {
"three"
}
}
```
### 構建器風格的方法編寫中返回 `Unit`
``` kotlin
fun arrayOfMinusOnes(size: Int): IntArray {
return IntArray(size).apply { fill(-1) }
}
```
### 單表達式函數
``` kotlin
fun theAnswer() = 42
```
這個等同于
``` kotlin
fun theAnswer(): Int {
return 42
}
```
還可以結合其它的形式得到更簡練的代碼。例如與 `when` 表達式一起:
``` kotlin
fun transform(color: String): Int = when (color) {
"Red" -> 0
"Green" -> 1
"Blue" -> 2
else -> throw IllegalArgumentException("Invalid color param value")
}
```
### 在一個對象上調用多個方法(`with`)
### Calling multiple methods on an object instance ('with')
``` kotlin
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()
}
```
### Java 7 的 try with 資源
``` kotlin
val stream = Files.newInputStream(Paths.get("/some/file.txt"))
stream.buffered().reader().use { reader ->
println(reader.readText())
}
```