1.创建DTOs(POJOs/POCOs)
data class Customer(val name: String, val email: String)
创建一个Customer类需要提供下面功能:
getters 为所有的属性提供getters(为var类型提供setters, val类型不可变,不需要提供)
equals()
hashcode()
toString()
copy()
component1(), component2(), …, for all properties (see Data classes)
2. 为函数提供默认参数
fun foo(a: Int = 0, b: String){
println("a: ${a}, b: ${b}")
}
3. 过滤一个列表
var posi = lists.filter { a->a.startsWith('a') }
或者更简洁:
posi = lists.filter { it.startsWith('a') }
4. String插入
println("Name $name")
5. 示例检查
when (x) {
is Foo -> ...
is Bar -> ...
else -> ...
}
6. 打印map和或者list
var maps = mapOf("a" to 1, "b" to 2, "c" to 3)
for((k,v) in maps){
println("k: ${k}, v: ${v}")
}
7. 使用'范围'
for(i in 1..100) {
print("${i} ")
}
for(i in 1 until 10) {
}
for(x in 1..10 step 2) {
}
for(x in 10 downTo 1) {
}
var x = 3
if (x in 1..10) {
println("xxx in")
}
8. 只读list(注意var和val区别)
val list = listOf("a", "b", "c")
9. 只读map
val map = mapOf("a" to 1, "b" to 2, "c" to 3)
10. 访问map
var maps = mapOf("a" to 1, "b" to 2, "c" to 3)
println(maps["b"])
11. 懒汉式属性?
val p: String by lazy {
// compute the string
}
12. 扩展功能(个人觉得比较强大,类似于注入?)
fun String.testAddMethod(){
println(this)
}
"abcd".testAddMethod()
13. 单例
object Resource {
val name = "name Resource"
}
14. if != null的快速写法
val files = listOf("a", "b", "c")
println(files?.size)
15. if else 快速写法
fun getNil():String?{
return null
}
fun main(args: Array<String>) {
var files = getNil()
println(files?.length?: "empty")
}
16. 如果为null执行一段语句
files?:println("is null")
17. 如果不为null执行一段语句
files?.let { println("not null") }
18. 通过when语句返回
var string = "b"
println(when(string) {
"a" ->0
"b" ->1
else -> 100
})
19. try/catch表达式
fun test() {
val result = try {
count()
} catch (e: ArithmeticException) {
throw IllegalStateException(e)
} // Working with result}
20. if表达式
val a = 2
var result = if(a == 1) {
"one"
} else if(a == 2) {
"two"
}else {
"three"
}
21. 使用构造者模式
fun arrayMinusOnes(size: Int):IntArray {
return IntArray(size).apply { fill(-1) }
}
22. 单一表达式函数
fun single(size: Int) = size * 10
相当于是:
fun single(size: Int): Int {
return size * 4
}
这个可以和其他约定一起组合,产生更简短的代码,比如when表达式:
fun transfrom(color: Int):String = when (color) {
1-> "red"
2-> "blue"
else-> "other color"
}
23. 调用一个对象的多个方法使用with
省略了obj.xxx()
fun main(args: Array<String>) {
val kotlin = RunKotlin()
with(kotlin) {
penDown()
println("zzz")
forward(2.0)
}
}
class RunKotlin {
fun penDown(){println("penDown")}
fun penUp(){println("penUp")}
fun turn(degress: Double){println(degress)}
fun forward(pixels: Double){println(pixels)}
}
24. Java 7's try with resources
val stream = Files.newInputStream(Paths.get("/some/file.txt"))
stream.buffered().reader().use {
reader -> println(reader.readText())
}
25. Convenient form for a generic function that requires the generic type information
/ 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)
26. 构造可能为null的布尔值
val b: Boolean? = ...
if (b == true) {
...
} else {
// `b` is false or null
}
转载于:https://blog.51cto.com/483181/1931893