天天看點

Kotlin上手(一)

标準函數with

with函數接收兩個參數,第一個參數是任意類型的對象,第二個是Lambda表達式。with函數會在Lambda表達式中提供第一個參數的上下文,并使用Lambda表達式中的最後一行代碼作為傳回值傳回。

fun test() {
        val list = listOf("Apple", "Banana", "Orange")
        val result = with(StringBuilder()) {
            append("開始吃水果")
            for (fruit in list) {
                append(fruit).append("\n")
            }
            append("水果都被吃完了")
            toString()
        }
        println(result)
    }
           

标準函數run

run函數不能直接調用,一定要調用某個對象的run函數才行,run函數隻接收一個Lambda表達式作為參數,并且會在Lambda表達式中提供上下文,并把Lambda表達式的最後一行代碼作為傳回值傳回

val list = listOf("Apple", "Banana", "Orange")
        val result = StringBuilder().run {
            append("開始吃水果\n")
            for (fruit in list) {
                append(fruit).append("\n")
            }
            append("水果被吃完")
            toString()
        }
        println(result)
           

标準函數apply

同樣是在某個對象上調用,并接收一個Lambda表達式作為參數,但無法指定傳回值

val intent = Intent(context,MainActivity::class.java).apply { 
            putExtra("param1","1")
            putExtra("param2","2")
        }
           

延遲初始化

private lateinit var adapter: RecyclerListAdapter

    private fun init() {
        adapter = RecyclerListAdapter()
    }
           

判斷是否已經完成了初始化

if (!::adapter.isInitiallized) {
	adapter = RecyclerListAdapter()
}
           

密封類

它是一個可繼承的類,Kotlin編譯器會自動檢查密封類有哪些子類,并強制要求将每一個子類所對應的條件全部處理。密封類及其子類隻能定義在同一個檔案的頂層位置,不能嵌套在其他類中。

sealed class Result

class Success(val msg: String) : Result()

class Failure(val error: Exception) : Result()

fun getResultMsg(result: Result) = when (result) {
    is Success -> result.msg
    is Failure -> "Error is ${result.error.message}"
}
           
sealed class MsgViewHolder(view: View): RecyclerView.ViewHolder(view)

class LeftViewHolder(view: View): MsgViewHolder(view)

class RightViewHolder(view: View): MsgViewHolder(view)

class MsgAdapter(val msgList: List<String>): RecyclerView.Adapter<MsgViewHolder>() {
    override fun onBindViewHolder(holder: MsgViewHolder, position: Int) {
        val msg = msgList[position]
        when (holder) {
            is LeftViewHolder -> holder.leftMsg = msg.leftText
            is RightViewHolder -> holder.rightMsg = msg.rightText
        }
    }
}
           

擴充函數

fun Any.log() {
    Log.d("測試日志", this.toString())
}

fun test1() {
    "Kotlin擴充函數真牛".log()
}
           

運算符重載

class Money(val value: Int) {

    operator fun plus(money: Money): Money {
        val sum = value + money.value
        return Money(sum)
    }
}

fun test2() {
    val money1 = Money(5)
    val money2 = Money(10)
    val money3 = money1 + money2
    println(money3.value)
}
           

多重重載

class Money(val value: Int) {

    operator fun plus(money: Money): Money {
        val sum = value + money.value
        return Money(sum)
    }

    operator fun plus(newValue: Int): Money {
        val sum = value + newValue
        return Money(sum)
    }
}

fun test2() {
    val money1 = Money(5)
    val money2 = Money(10)
    val money3 = money1 + money2
    val money4 = money3 + 20
    println(money4.value)
    println(money3.value)
}