原文 http://www.kotlinlang.org/docs/reference/idioms.html

习惯语法

(语法糖?)

常用的kotlin习语,如果你有更好的语法习惯,可以提交pull request贡献出来。

创建DTO’s (POJO’s/POCO’s)

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

Customer 默认提供了以下函数:
— 所有属性都具有 getter (var声明的还有setter) 方法
equals()
hashCode()
toString()
copy()
component1() ,component2() 所有属性都有(详情 Data classes)

函数的默认参数

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

过滤list集合:

  1. val positives = list.filter { x -> x > 0 }

或者更简短的:

  1. val positives = list.filter { it > 0 }

String 插入

  1. println("Name $name")

类型检查

  1. when (x) {
  2. is Foo -> ...
  3. is Bar -> ...
  4. else -> ...
  5. }

遍历list/map键值对

  1. val list =arrayListOf("a","b","c")
  2. for (v in list) {
  3. println("$v")
  4. }
  5. val map=hashMapOf(Pair("a",1), Pair("b","cd"))
  6. for ((k, v) in map) {
  7. println("$k -> $v")
  8. }

k,v 可以任意使用

使用 ranges

  1. for (i in 1..100) { ... }
  2. for (x in 2..10) { ... }

不可变 list

  1. val list = listOf("a", "b", "c")

不可变 map

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

访问读取 map

  1. println(map["key"])
  2. map["key"] = value

Lazy property

懒属性?

  1. val p: String by lazy {
  2. // compute the string
  3. }

扩展函数

  1. fun String.spaceToCamelCase() { ... }
  2. "Convert this to camelcase".spaceToCamelCase()

创建单例

常量

  1. object Resource {
  2. val name = "Name"
  3. }
  4. println(Resource.name)

安全调用对象

  1. val files = File("Test").listFiles()
  2. println(files?.size) //如果files为null也不会抛出异常

为null时else块

  1. val files = File("Test").listFiles()
  2. println(files?.size ?: "empty")

如果为null的执行

  1. val data = ...
  2. val email = data["email"] ?: throw IllegalStateException("Email is missing!")

执行不为null的代码块

  1. val data = ...
  2. data?.let {
  3. ... // 如果不为null会执行这里的代码
  4. }

返回when声明

  1. fun transform(color: String): Int {
  2. return when (color) {
  3. "Red" -> 0
  4. "Green" -> 1
  5. "Blue" -> 2
  6. else -> throw IllegalArgumentException("Invalid color param value")
  7. }
  8. }

‘try/catch’ 块

  1. fun test() {
  2. val result = try {
  3. count()
  4. } catch (e: ArithmeticException) {
  5. throw IllegalStateException(e)
  6. }
  7. // Working with result
  8. }

if 表达式

  1. fun foo(param: Int) {
  2. val result = if (param == 1) {
  3. "one"
  4. } else if (param == 2) {
  5. "two"
  6. } else {
  7. "three"
  8. }
  9. }

返回方法生成器

  1. fun arrayOfMinusOnes(size: Int): IntArray {
  2. return IntArray(size).apply { fill(-1) }
  3. }

单个的函数返回值表达式

  1. fun theAnswer() = 42

这相当于:

  1. fun theAnswer(): Int {
  2. return 42
  3. }

这可以与其它特有语法有效地结合起来,从而使用更简短的代码。例如使用when 表达式:

  1. fun transform(color: String): Int = when (color) {
  2. "Red" -> 0
  3. "Green" -> 1
  4. "Blue" -> 2
  5. else -> throw IllegalArgumentException("Invalid color param value")
  6. }

使用wich串联调用对象的多个方法

  1. class Turtle {
  2. fun penDown()
  3. fun penUp()
  4. fun turn(degrees: Double)
  5. fun forward(pixels: Double)
  6. }
  7. val myTurtle = Turtle()
  8. with(myTurtle) { //draw a 100 pix square
  9. penDown()
  10. for(i in 1..4) {
  11. forward(100.0)
  12. turn(90.0)
  13. }
  14. penUp()
  15. }

Java 7 的try 块自动释放资源

  1. val stream = Files.newInputStream(Paths.get("/some/file.txt"))
  2. stream.buffered().reader().use { reader ->
  3. println(reader.readText())
  4. }