Fork me on GitHub

kotlin学习笔记2

Idioms

创建JavaBean(DTO,POJO etc)

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

data class 自动提供了

  • getter(setter for vals)

  • equals, hashCode, toString, copy, componentX方法

函数参数的默认值

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

filter a list

val positives = list.filter { x -> x>0} // 过滤出大于零的值,另外,这种语法类似于ruby

// shorter
val positives_1 = list.filter { it > 0 }

Instance check

// 对了,when实际上实现了switch的功能
when (x) {
is Foo -> ...
is Bar -> ...
else -> ...
}

key-value遍历map

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

range

for (i in 1..100) { ... } // closed range: includes 100
for (i in 1 until 100) { ... } // half-open range: does not include 100
for (x in 2..10 step 2) { ... }
for (x in 10 downTo 1) { ... }
if (x in 1..10) { ... }

不可变容器

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

惰性求值

val p: String by lazy {
// compute the string
}

函数扩展

fun String.spaceToCamelCase() { ... }

"Convert this to camelcase".spaceToCamelCase()

单例

object Resource { // 和scala语法一致
val name = "Name"
}

with

class Turtle {
fun penDown()
fun penUp()
fun turn(degrees: Double)
fun forward(pixels: Double)
}

val myTurtle = Turtle()
with(myTurtle) { //draw a 100 pix square
penDown()
for(i in 1..4) {
forward(100.0)
turn(90.0)
}
penUp()
}

resource

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

泛型

// public final class Gson {
// ...
// public T fromJson(JsonElement json, Class classOfT) throws JsonSyntaxException {
// ...

inline fun Gson.fromJson(json: JsonElement): T = this.fromJson(json, T::class.java)
posted @ 2017-11-20 16:50  alchimistin  阅读(174)  评论(0编辑  收藏  举报