Kotlin常用语法糖
1. let, run, apply
2. string template
Kotlin在背后实际创建了一个StringBuilder来实现
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的值就是返回值
4. 区间
val range = 1..10
从1到10,包括1和10
for (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的类都可以做此比较
浙公网安备 33010602011771号