Kotlin經常使用語法糖

1. let, run, applyexpress

 

2. string templateapp

  Kotlin在背後實際建立了一個StringBuilder來實現ui

    val name = "WANG"
    println("greetings, $name")

  // use "\" to escape
  val amount = "5"
  println("The price is \$$amount")

  // more complex
  val score = 66
  println("""${if(score > 60) "Congratulation!" else "Sorry"}, Nick""")

 

3. 在if,when,lambda表達式等存在返回值的狀況下,對應代碼塊的最後一條expression的值就是返回值spa

 

4. 區間code

val range = 1..10
從1到10,包括1和10for (i in 1..10) {    //}for (i in 100 downTo 1) {    //}for (i in 1..10 step 2) {    //}for (i in 100 downTo 1 step 3) {    //}a until b 等同於 a..(b-1)if (a in 1..10) {    //}if (a !in 1..10) {    //}fun check(c: Char): String = when(c) {    in 'a'..'z' -> "lower case alphabet"    in 'A'..'Z' -> "Upper case alphabet"    else -> "Not sure"}boolean isSo = "china" in "america".."russia"這個等同於 "china" >= "america" && "china" <= "russia"全部實現了Comparable的類均可以作此比較
相關文章
相關標籤/搜索