Kotlin入门之常用Idioms(风格、术语)
2017-05-20 本文已影响24人
已迁至知乎_此不再维护
该文章记录了Kotlin中经常使用的Idioms集合。如果你有常用术语,欢迎作出贡献。
创建DTO数据传入对象(POJOs/POCOs)
data class Customer(val name: String, val email: String)
上述代码提供的Customer类默认具有如下函数:
- getters (and setters in case of vars) for all properties
- equals()
- hashCode()
- toString()
- copy()
- component1(), component2(), …, for all properties
为函数形参定义默认值
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")
}
k,v可以被任意命名
使用范围
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) { ... }
只读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
懒属性
val p: String by lazy {
// compute the string
}
扩展函数
fun String.spaceToCamelCase() { ... }
"Convert this to camelcase".spaceToCamelCase()
创建单例
object Resource {
val name = "Name"
}
非null调用的缩写
val files = File("Test").listFiles()
println(files?.size)
非null调用,否则其他的缩写
val files = File("Test").listFiles()
println(files?.size ?: "empty")
为null执行表达式
val data = ...
val email = data["email"] ?: throw IllegalStateException("Email is missing!")
非null执行
val data = ...
data?.let {
... // execute this block if not null
}
return表达式
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) {
throw IllegalStateException(e)
}
// Working with result
}
if表达式
fun foo(param: Int) {
val result = if (param == 1) {
"one"
} else if (param == 2) {
"two"
} else {
"three"
}
}
Builder-style usage of methods that return Unit
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) { //draw a 100 pix square
penDown()
for(i in 1..4) {
forward(100.0)
turn(90.0)
}
penUp()
}
Java 7's try with resources(Java7的资源尝试)
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)
使用一个可null的Boolean类型的值
val b: Boolean? = ...
if (b == true) {
...
} else {
// `b` is false or null
}