习惯用法
一些Kotlin中广泛使用的语法习惯
data class
1 | data class Customer(val name: String, val email: String) |
会为 Customer 类提供以下功能:
- 所有属性的 getters (对于var定义的还有setters)
- equals()
- hashCode()
- toString()
- copy()
- 所有属性的 component1(). component2()…等
函数的默认参数
1 | fun foo(a: Int = 0, b: String = "") {...} |
过滤list
1 | val list = listOf(1, 2, 3, 4, 5) |
检查元素是否在集合中
1 | if ("abc" in list) {...} |
遍历 map/pair型list
1 | val map = mapOf(0 to "秦", 1 to "川", 2 to "小", 3 to "将") |
使用单例
1 | object Resource { |
if not null
1 | val files = File("test").listFiles() |