标签:files file 表达式 otl 访问 单表 不为 lstat 简化
fun foo(a: Int = 0,b: String = ""){......}
var positives = list.filter {x -> x > 0}
或者可以更短
var positives = list.filter { it > 0 }
println("Name $name")
when (x) { is Foo //-> …… is Bar //-> …… else //-> …… }
for ((k, v) in map) { println("$k -> $v") }
k、v可以改成任意名字。
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) { …… } if (x in 1..10) { …… }
val list = listOf("a", "b", "c")
val map = mapOf("a" to 1, "b" to 2, "c" to 3)
println(map["key"])
map["key"] = value
val p: String by lazy { // 计算该字符串 }
fun String.spaceToCamelCase() { …… }
"Convert this to camelcase".spaceToCamelCase()
object Resource { val name = "Name" }
val files = File("Test").listFiles()
println(files?.size)
val files = File("Test").listFiles()
println(files?.size ?: "empty")
val values = …… val email = values["email"] ?: throw IllegalStateException("Email is missing!")
val emails = …… // 可能会是空集合 val mainEmail = emails.firstOrNull() ?: ""
val value = …… value?.let { …… // 代码会执?到此处, 假如data不为null }
val value = ……
val mapped = value?.let { transformValue(it) } ?: defaultValueIfValueIsNull
fun transform(color: String): Int { return when (color) { "Red" -> 0 "Green" -> 1 "Blue" -> 2 else -> throw IllegalArgumentException("Invalid color param value") } }
fun test() { val result = try { count() } catch (e: ArithmeticException) { throw IllegalStateException(e) } // 使? result }
fun foo(param: Int) { val result = if (param == 1) { "one" } else if (param == 2) { "two" } else { "three" } }
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") }
class Turtle { fun penDown() fun penUp() fun turn(degrees: Double) fun forward(pixels: Double) } val myTurtle = Turtle() with(myTurtle) { // 画?个 100 像素的正?形 penDown() for(i in 1..4) { forward(100.0) turn(90.0) } penUp() }
val b: Boolean? = …… if (b == true) { …… } else { // `b` 是 false 或者 null }
var a = 1 var b = 2 a = b.also { b = a }
标签:files file 表达式 otl 访问 单表 不为 lstat 简化
原文地址:https://www.cnblogs.com/zxpy/p/10528496.html