kotlin 学习记录 基本语法 (2)

https://huanglizhuo.gitbooks.io/kotlin-in-chinese/content/GettingStarted/Basic-Syntax.html

使用循环

fun main(args: Array<String>) {
  val items = listOf("apple", "banana", "kiwi")
  for (item in items) {
    println(item)
  }
}

或者

fun main(args: Array<String>) {
  val items = listOf("apple", "banana", "kiwi")
  for (index in items.indices) {
    println("item at $index is ${items[index]}")
  }
}

使用 while 循环

fun main(args: Array<String>) {
  val items = listOf("apple", "banana", "kiwi")
  var index = 0
  while (index < items.size) { println("item at $index is ${items[index]}") index++ } } 

参看while循环

使用 when 表达式

fun describe(obj: Any): String =
when (obj) {
  1          -> "One"
  "Hello"    -> "Greeting"
  is Long    -> "Long"
  !is String -> "Not a string"
  else       -> "Unknown"
}

fun main(args: Array<String>) {
  println(describe(1))
  println(describe("Hello"))
  println(describe(1000L))
  println(describe(2))
  println(describe("other"))
}

参看when表达式

+

使用ranges

使用 in 操作符检查数值是否在某个范围内:

+

fun main(args: Array<String>) {
  val x = 10
  val y = 9
  if (x in 1..y+1) {
      println("fits in range")
  }
}

检查数值是否在范围外:

+

fun main(args: Array<String>) {
  val list = listOf("a", "b", "c")

  if (-1 !in 0..list.lastIndex) {
    println("-1 is out of range")
  }
  if (list.size !in list.indices) {
    println("list size is out of valid list indices range too")
  }
}

在范围内迭代:

+

fun main(args: Array<String>) {
  for (x in 1..5) {
    print(x)
  }
}

或者使用步进:

+

fun main(args: Array<String>) {
  for (x in 1..10 step 2) {
    print(x)
  }
  for (x in 9 downTo 0 step 3) {
    print(x)
  }
}

参看Ranges

+

使用集合

对一个集合进行迭代:

+

fun main(args: Array<String>) {
  val items = listOf("apple", "banana", "kiwi")
  for (item in items) {
    println(item)
  }
}

使用 in 操作符检查集合中是否包含某个对象

+

fun main(args: Array<String>) {
  val items = setOf("apple", "banana", "kiwi")
  when {
    "orange" in items -> println("juicy")
    "apple" in items -> println("apple is fine too")
  }
}

使用lambda表达式过滤和映射集合:

+

fun main(args: Array<String>) {
  val fruits = listOf("banana", "avocado", "apple", "kiwi")
  fruits
    .filter { it.startsWith("a") }
    .sortedBy { it }
    .map { it.toUpperCase() }
    .forEach { println(it) }
}

你可能感兴趣的:(kotlin 学习记录 基本语法 (2))