kotlin

来源:互联网 发布:latex for windows 编辑:程序博客网 时间:2024/05/21 07:45

创建数据传输对象(DTO)

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

以上声明为Customer类型提供下列功能:

  • 每个属性拥有getter(如果使用var定义,也同时拥有setter)
  • equals()
  • toString()
  • copy()
  • 所有属性依次对应component1() , component2() , …

函数参数默认值

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

过滤列表

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

或者可以更加简洁:

val positives = list.filter { it > 0 }

字符串插入

println("Name $name")

实例检查

when (x) {  is Foo -> ...  is Bar -> ...  else -> ...}

遍历含键值对的map或list

for ((k, v) in map) {  println("$k -> $v")}

使用范围(Range)

for (i in 1..100) { ... } // 闭合的范围:包括100for (i in 1 until 100) { ... } // 半开的范围:不包括100for (x in 2..10 step 2) { ... } // 指定步长for (x in 10 downTo 1) { ... } // 反向的范围if (x in 1..10) { ... } // 在条件语句中使用

只读list

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

只读map

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

访问map

println(map["key"])map["key"] = value

lazy属性

val p: String by lazy {  // 只会被执行一次,下次访问时返回第一次的计算结果}

扩展函数

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

创建单例(singleton)

object Resource {  val name = "Name"}

If Not Null的简化表达

val files = File("Test").listFiles()println(files?.size)

为空时执行语句

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

非空时执行语句

val data = ...data?.let {  ... // execute this block if not null}

when表达式

fun transform(color: String): Int {  return when (color) {    "Red" -> 0    "Green" -> 1    "Blue" -> 2    else -> throw IllegalArgumentException("Invalid color param value")  }}

try/catch表达式

fun test() {  val result = try {    count()  } catch (e: ArithmeticException) {    -1  }   // Working with result}

if表达式

fun foo(param: Int) {  val result = if (param == 1) {    "one"  } else if (param == 2) {    "two"  } else {    "three"  }}

在Builder风格下使用方法

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

单表达式函数

fun theAnswer() = 42

等同于

fun theAnswer(): Int {  return 42}

这可以与其它形式进行结合,带来更短的代码。比如与when表达式结合:

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

在一个对象实例上调用多个方法(使用with

class Turtle {  fun penDown()  fun penUp()  fun turn(degrees: Double)  fun forward(pixels: Double)} val myTurtle = Turtle()with(myTurtle) {   penDown()  for(i in 1..4) {    forward(100.0)    turn(90.0)  }  penUp()}

Java7的try with resources

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

需要类型信息的泛型函数的简便形式:

// public final class Gson {//   ...//   public <T> T fromJson(JsonElement json, Class<T> classOfT) throws JsonSyntaxException {//   ...inline fun <reified T: Any> Gson.fromJson(json): T = this.fromJson(json, T::class.java)

使用可空的布尔对象

val b: Boolean? = ...if (b == true) {  ...} else {  // b 为 false或 null}