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的类均可以作此比较
相关文章
相关标签/搜索