鍍金池/ 教程/ Android/ Kotlin慣用語法
Kotlin內聯函數
Kotlin開發(fā)環(huán)境設置(Eclipse)
Kotlin調用Java代碼
Kotlin使用Ant
Kotlin編譯器插件
Kotlin相等性
Kotlin JavaScript模塊
編寫Kotlin代碼文檔
Kotlin返回和跳轉
Kotlin異常處理
Kotlin可見性修飾符
Kotlin委托
Kotlin委托屬性
Kotlin編碼約定/編碼風格
Kotlin基礎語法
使用Kotlin進行服務器端開發(fā)
Kotlin接口
Kotlin反射
Kotlin類型別名
Kotlin枚舉類
Kotlin當前版本是多少?
Kotlin注解處理工具
Kotlin類型的檢查與轉換
Kotlin屬性和字段
Kotlin類型安全的構建器
Kotlin相比Java語言有哪些優(yōu)點?
Kotlin JavaScript反射
Kotlin 是什么?
Kotlin泛型
Kotlin慣用語法
Kotlin與OSGi
Kotlin數據類型
Kotlin是面向對象還是函數式語言?
Kotlin動態(tài)類型
Kotlin協(xié)程
Kotlin操作符符重載
Kotlin使用Gradle
Kotlin密封類
Kotlin兼容性
Kotlin集合
Kotlin調用JavaScript
Kotlin null值安全
Kotlin函數
Kotlin開發(fā)環(huán)境設置(IntelliJ IDEA)
Kotlin嵌套類
Kotlin控制流程
Kotlin和Java語言比較
Kotlin 與 Java 語言兼容嗎?
Kotlin教程
Kotlin類和繼承
Kotlin對象表達式和對象聲明
JavaScript中調用Kotlin
Kotlin區(qū)間/范圍
Kotlin數據類
Kotlin lambda表達式
Kotlin是免費的嗎?
Kotlin包
使用Kotlin進行Android開發(fā)
在Java中調用Kotlin代碼
Kotlin this表達式
使用Kotlin進行JavaScript開發(fā)
Kotlin擴展
Kotlin解構聲明
Kotlin注解
Kotlin使用Maven

Kotlin慣用語法

Kotlin中有很多經常使用慣用語法,如果你有一個最喜歡的慣用語法,那就貢獻它吧。 做一個拉請求。

創(chuàng)建DTO(POJO/POCO)

data class Customer(val name: String, val email: String)

假設Customer類提供以下功能:

  • 所有屬性的gettersetter
  • 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) { ... }  // closed range: includes 100
for (i in 1 until 100) { ... } // half-open range: does not include 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 {
    // compute the string
}

擴展函數

fun String.spaceToCamelCase() { ... }

"Convert this to camelcase".spaceToCamelCase()

創(chuàng)建單例

object Resource {
    val name = "Name"
}

如果不為null的速記

val files = File("Test").listFiles()

println(files?.size)

如果不為nullelse的速記

val files = File("Test").listFiles()

println(files?.size ?: "empty")

如果為null,執(zhí)行語句

val data = ...
val email = data["email"] ?: throw IllegalStateException("Email is missing!")

如果不為null,執(zhí)行語句

val data = ...

data?.let {
    ... // execute this block if not null
}

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)
    }

    // Working with result
}

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-expression結合:

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()
}

Java 7的try與資源的用法

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` is false or null
}

上一篇:Kotlin委托下一篇:Kotlin基礎語法