创建 DTO (POJO/POCO)

1
data class Customer(val name: String, val email: String)

会为 Customer 类提供以下功能:

所有属性的 getter (对于 var 定义的还有 setter)

  • equals()
  • hashCode()
  • toString()
  • copy()
  • 所有属性的 component1()、 component2()……等等

可以设置函数的默认参数,同样该默认参数也可以设置在类中。

1
fun foo(a: Int = 0, b: String = "") { …… }

过滤list列表

使用filter方法。

1
2
3
val positives = list.filter { x -> x > 0 }
//或者更短
val positives = list.filter { it > 0 }

map的使用方法

1
val map = mapOf("a" to 1, "b" to 2, "c" to 3)

访问map条目

1
2
print(map["key"])
map["key"] = value

区间迭代

1
2
3
4
5
for (i in 1..100) { …… }  // 闭区间:包含 100
for (i in 1 until 100) { …… } // 半开区间:不包含 100
for (x in 2..10 step 2) { …… }
for (x in 10 downTo 1) { …… }
(1..10).forEach { …… }