有趣的kotlin语法
1.数组过虑.
val positives = list.filter { it > 0 }
2.范围的使用
for (i in 1..100) { ... }
for (i in 1 until 100) { ... }
for (x in 2..10 step 2) { ... }
for (x in 10 downTo 1) { ... }
if (x in 1..10) { ... }
- Read-only list
val list = listOf("a", "b", "c")
- Read-only map
val map = mapOf("a" to 1, "b" to 2, "c" to 3)
5.访问数组,这个比java访问方便多了
map["key"] = value
- Extension Functions
fun String.spaceToCamelCase() { ... }
"Convert this to camelcase".spaceToCamelCase()
- Creating a singleton
object Resource {
val name = "Name"
}
数组中好用的方法
- 快捷过来数组中的空元素 filterNotNull()
val nullableList: List<Int?> = listOf(1, 2, null, 4) val intList: List<Int> = nullableList.filterNotNull()