创建DTOs(POJOs/POCOs)
data class Customer(val name: String, val email: String)
Customer类拥有以下方法:
- getters (and setters in case of
var
s) for all properties - equals()
- hashCode()
- toString()
- copy()
- component1(),component2(), ..., for all properties (see Data classes)
函数参数缺省值
fun foo(a: Int = 0, b: String = "") { ... }
list filter
val positives = list.filter { x -> x > 0 }
val positives = list.filter { it > 0 }
判断集合中是否存在某元素
if ("john@example.com" in emailsList) { ... }
if ("jane@example.com" !in emailsList) { ... }
模板字符串
println("Name $name")
实例类型判断
when (x) {
is Foo -> ...
is Bar -> ...
else -> ...
}
只读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
遍历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) { ... }
延迟属性Lazy
val p: String by lazy {
// compute the string
}
val lazyValue: String by lazy {
println("computed!")
"Hello"
}
fun main(args: Array<String>) {
println(lazyValue)
println(lazyValue)
}
输出结果为
computed!
Hello
Hello
第一次调用get() 会执行已传递给 lazy() 的 lambda 表达式并记录结果, 后续调用get() 只是返回记录的结果。
Extension Function
fun String.spaceToCamelCase() { ... }
"Convert this to camelcase".spaceToCamelCase()
Extension function可以为任何一个Class加上function,却不必更改该Class的源码。
单例
object Resource {
val name = "Name"
}
初始化抽象class
abstract class MyAbstractClass {
abstract fun doSomething()
abstract fun sleep()
}
fun main() {
val myObject = object : MyAbstractClass() {
override fun doSomething() {
// ...
}
override fun sleep() { // ...
}
}
myObject.doSomething()
}
if-not-null简写
val files = File("Test").listFiles()
println(files?.size) // size is printed if files is not null
if-not-null-else 简写
val files = File("Test").listFiles()
println(files?.size ?: "empty") // if files is null, this prints "empty"
if-null执行语句
val values = ...
val email = values["email"] ?: throw IllegalStateException("Email is missing!")
获取集合(集合可能为空)中第一个元素
val emails = ... // might be empty
val mainEmail = emails.firstOrNull() ?: ""
if not null执行
val value = ...
value?.let {
... // execute this block if not null
}
if not null map操作
val value = ...
val mapped = value?.let { transformValue(it) } ?: defaultValue
// defaultValue is returned if the value or the transform result is 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) {
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风格
fun arrayOfMinusOnes(size: Int): IntArray {
return IntArray(size).apply { fill(-1) }
}
Single-expression 方法
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()
}
配置对应的属性
val myRectangle = Rectangle().apply {
length = 4
breadth = 5
color = 0xFAFAFA
}
Java7的try-with-resources
val stream = Files.newInputStream(Paths.get("/some/file.txt"))
stream.buffered().reader().use { reader ->
println(reader.readText())
}
泛型
class Box<T>(t : T) {
var value = t
}
fun main(){
val intBox = Box<Int>(1)
val stringBox = Box<String>("Evan")
println(intBox.value)
println(stringBox.value)
}
Nullable Boolean
val b: Boolean? = ...
if (b == true) {
...
} else {
// `b` is false or null
}
交换变量
var a = 1
var b = 2
a = b.also { b = a }
TODO
fun calcTaxes(): BigDecimal = TODO("Waiting for feedback from accounting")
网友评论