序
字符串字面值及模板
字符串字面值
1
2
3
4
5
6
7
8
9
10
11
|
@Test fun testStringLiterals(){ val a = "" " if (a > 1 ) { | return a |} "" ".trimMargin() println(a) val b = "" "Foo Bar "" ".trimIndent() println(b) } |
有了字符串字面值,寫sql啥的就不用那么費勁拼接字符串了
字符串模板
1
2
3
4
5
6
7
|
@Test fun testStringTemplate() { val name = "hello kotlin" println( "Hello, $name!" ); val data = listOf( 1 , 2 , 3 ) println( "Hello, ${data[0]}!" ) } |
這個字符串模板更是強大,相當于內置一個freemarker,而且都不用手工傳遞變量值
for循環中獲取當前index
1
2
3
4
5
6
7
|
@Test fun testForEachIndex(){ val items = listOf( "apple" , "banana" , "kiwifruit" ) for (index in items.indices) { println( "item at $index is ${items[index]}" ) } } |
在java里頭for each循環要得到index,就得在外面聲明下index,自己統計,太別扭了
data class
1
2
3
4
5
6
7
8
9
|
//生成getter/setter,equals,hashcode,toString,copy等 //setter是var變量才有 data class Customer(val name: String, val email: String) @Test fun testDataClass(){ val customer = Customer( "admin" , "admin@admin.com" ) println(customer) } |
java總是要聲明getter/setter,好處是可以在IDE查找那些方法有調用getter/setter;
lombok雖然可以自動生成getter/setter,@Data注解也可以生成equal/hashcode方法,但是lombok不方便在IDE查找那些方法有調用getter/setter;kotlin的data class幫你解決這些問題
Null Safety
1
2
3
4
5
6
7
8
9
10
11
|
@Test fun testIfNotNull(){ val files = File( "Test" ).listFiles() println(files?.size) //null } @Test fun testIfNotNullAndElse(){ val files = File( "Test" ).listFiles() println(files?.size ?: "empty" ) } |
這個Null Safety太有用了,比起java的三元表達式更簡潔一點,在表達式為true的時候就不用重復寫要返回的內容,只要寫else部分。
Null Safety在流式/鏈式調用的時候更有用
1
2
|
// 如果 `person` 或者 `person.department` 其中之一為空,都不會調用該函數: person?.department?.head = managersPool.getManager() |
小結
本文只是舉了kotlin可以改善java代碼的幾個例子,kotlin太強大了,目標是要替代java。其中很多設計可以看到scala的影子,但是黑魔法也比較多,學習曲線稍微有點抖,不過如果不使用太高級的語法,也還OK。
相關參考:https://www.kotlincn.net/docs/reference/
原文鏈接:https://segmentfault.com/a/1190000014052524