Kotlin 基本语法 (二)

地址:http://kotlinlang.org/docs/reference/basic-syntax.html#using-a-while-loop

使用 while 循环

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      -> "Unknow"
}
译者按:这个表达式很像 switch 语句,不过能处理的类型比较宽泛

详情查看when 表达式

使用 ranges

使用 in 操作符来判断一个 number 是否在某个范围

val x = 10
val y = 9
if (x in 1..y+1) {
  println("fits in range")
}

检查一个数字是否超出某个范围

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

遍历一个 范围

for (x in 1..5) {
  print(x)
}

设置遍历节奏

for (x in 1..10 step 2) {
  print(x)
}

for (x in 9 downTo 0 step 3) {  // 从 9 到 0,反序遍历,步长为 3 
  print(x)
}

详情查看Ranges

使用集合

遍历一个集合

for (item in items) {
  println(item)
}

检查一个集合是否包含某个元素

when {
  "orange" in items -> println("juicy")
  "apple" in items -> println("apple is fine too")
}

使用 lambda 表达式过滤和转化集合元素

fruits
.filter { it.startsWith("a") }
.sortedBy { it }
.map { it.toUpperCase() }
.forEach{ println(it) }

详情查看高阶函数 和 Lambda

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值