1、創建POJO
data class Customer(val name: String, val age: Int)
用data關鍵字創建的class相對應與java中的javabean對象類。此class默認包含以下方法:
(1)getters(如果變量爲var的則會有setters),針對每個屬性
(2)equals()
(3)hashCode()
(4)toString()
(5)copy()
(6)component1(), component2()….針對每個屬性。這個方法不對外部顯示,以後會詳細解釋。
2、方法參數的默認值
fun foo(a: Int = 0, b: String = ""){...}
3、List
(1)創建只讀的List,只能獲取list中的值,不能修改其中的值
val list = listOf("a", "b", "c")
list[0] = "d" //是不合法的
(2)創建可修改的List,每個index的值可讀可寫
val list = mutableListOf("a", "b", "c")
list[0] = "d" //是合法的,修改index爲0的值爲"d"
4、Map
(1)只讀的map
val map = mapOf("a" to 1, "b" to 2, "c" to 3)
map["a"] = 4 //是可不合法的
(2)可讀可寫的Map
val map = mutableMapOf(Pair("a", 1), Pair("b", 2), Pair("c", 3))
map["a"] = 4 //是合法的,並且修改了key爲"a"的值爲4
也可以初始化java的hashmap,也爲可讀可寫
val hashMap = hashMapOf("a" to 1, "b" to 2, "c" to 3)
hashMap["a"] = 4 //是合法的
5、擴展方法
在java中我們經常會寫一些Utils類,來對一些已知類的擴展使用,在kotlin中我們可以直接爲某個類寫一些擴展方法,在使用時就跟使用普通方法一樣。
fun String.firstChar(){
return if(length > 0) get(0) else nul
}
fun test(){
val c = "abc".firstChar()
println(c)
}
打印結果爲=====
a
6、判斷非空的簡寫(not null)
val files = File("test").listFiles()
println(files?.size) //如果files不爲空時獲取它的屬性size,如果爲空則返回null
7、操作符?:
val files = File("Test").listFiles()
println(files?.size ?: "empty") /** 如果files不爲Null時返回files.size,如果files爲null,則表達式files?.size爲null,會返回?:後面的值empty*/
//?:操作符表示如果左邊的表達式不爲null則返回左邊表達式的值,否則返回右邊表達式的值
8、返回when表達式
when表達式可以作爲一個返回值,如下代碼:
fun transform(color: String): Int {
return when(color) {
"red" -> 0 //// 如果符合條件則返回0
"green" -> 1
"blue" -> 2
else -> throw IllegalArgumentException("Invalid color param value")
}
}
9、try/cache表達式
fun test() {
val result = try {
count()
} catch (e: ArithmeticException) {
throw IllegalStateException(e)
}
// Working with result
}
10、if表達式
fun foo(param: Int) {
val result = if (param == 1) {
"one"
} else if (param == 2) {
"two"
} else {
"three"
}
}
11、單一表達式
fun theAnswer() = 42
12、調用一個對象實例的多個方法(with)
class Turtle {
fun penDown()
fun penUp()
fun turn(degrees: Double)
fun forward(pixels: Double)
}
fun callI(){
val myTurtle = Turtle()
with(myTurtle) { // 以下默認調用的都是myTurtle的方法
penDown()
for(i in 1..4){
forWard(100.0)
turn(90.0)
}
penUp()
}
}