語言風格
這里整理了 kotlin 慣用的代碼風格,如果你有喜愛的代碼風格,可以在 github 上給 kotlin 提 pull request 。
創建DTOs(POJSs/POCOs) 文件:
data class Customer(val name: String, val email: String)
上述代碼提供了一個包含以下功能的 Customer 類:
- getters (and setters in case of vars) for all properties
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")
類型實例檢查:
1 when (x) { 2 is Foo -> ... 3 is Bar -> ... 4 else -> ... 5 }
Map/List 的名值對遍歷:
1 for ((k, v) in map) { 2 println("$k -> $v") 3 }
k, v 的命名可以是任何字符
使用 Ranges(區間):
1 for (i in 1..100) { ... } // 閉區間: 包含 100 2 for (i in 1 until 100) { ... } // 半開區間: 不包含 100 3 for (x in 2..10 step 2) { ... } // x自增2 4 for (x in 10 downTo 1) { ... } // 倒序遍歷 5 if (x in 1..10) { ... } // x是否在區間
只讀List:
val list = listOf("a", "b", "c")
只讀Map:
1 val map = mapOf("a" to 1, "b" to 2, "c" to 3)
訪問Map:
1 println(map["key"]) 2 map["key"] = value
lazy屬性:
1 val p: String by lazy { 2 // compute the string 3 }
函數擴展:
1 fun String.spaceToCamelCase() { ... } 2 3 "Convert this to camelcase".spaceToCamelCase()
創建單例:
1 object Resource { 2 val name = "Name" 3 }
if 判空(null)的快捷方式:
1 val files = File("Test").listFiles() 2 3 println(files?.size)
有else:
1 val files = File("Test").listFiles() 2 3 println(files?.size ?: "empty")
如果為空則執行語句:
1 val data = ... 2 val email = data["email"] ?: throw IllegalStateException("Email is missing!")
為空則執行操作:
1 val data = ... 2 3 data?.let { 4 ... // execute this block if not null 5 }
在when語句里返回:
1 fun transform(color: String): Int { 2 return when (color) { 3 "Red" -> 0 4 "Green" -> 1 5 "Blue" -> 2 6 else -> throw IllegalArgumentException("Invalid color param value") 7 } 8 }
try/catch:
1 fun test() { 2 val result = try { 3 count() 4 } catch (e: ArithmeticException) { 5 throw IllegalStateException(e) 6 } 7 8 // Working with result 9 }
IF:
1 fun foo(param: Int) { 2 val result = if (param == 1) { 3 "one" 4 } else if (param == 2) { 5 "two" 6 } else { 7 "three" 8 } 9 }
生成器模式寫法返回 Unit :
1 fun arrayOfMinusOnes(size: Int): IntArray { 2 return IntArray(size).apply { fill(-1) } 3 }
單行表達式:
fun theAnswer() = 42
相當於:
1 fun theAnswer(): Int { 2 return 42 3 }
可以高效地與其他語法配合,是代碼更簡潔,如下面的 when :
1 fun transform(color: String): Int = when (color) { 2 "Red" -> 0 3 "Green" -> 1 4 "Blue" -> 2 5 else -> throw IllegalArgumentException("Invalid color param value") 6 }
使用 With 語句可以調用一個對象里的多個方法:
1 class Turtle { 2 fun penDown() 3 fun penUp() 4 fun turn(degrees: Double) 5 fun forward(pixels: Double) 6 } 7 8 val myTurtle = Turtle() 9 with(myTurtle) { //draw a 100 pix square 10 penDown() 11 for(i in 1..4) { 12 forward(100.0) 13 turn(90.0) 14 } 15 penUp() 16 }
支持Java 7 的文件操作方式:
1 val stream = Files.newInputStream(Paths.get("/some/file.txt")) 2 stream.buffered().reader().use { reader -> 3 println(reader.readText()) 4 }
為聲明需要泛型信息的泛型方法提供更為方便的格式:
1 // public final class Gson { 2 // ... 3 // public <T> T fromJson(JsonElement json, Class<T> classOfT) throws JsonSyntaxException { 4 // ... 5 6 inline fun <reified T: Any> Gson.fromJson(json): T = this.fromJson(json, T::class.java)
Boolean 值可以是null:
1 val b: Boolean? = ... 2 if (b == true) { 3 ... 4 } else { 5 // `b` is false or null 6 }
轉載請注明原文地址:http://www.cnblogs.com/joejs/p/6878128.html