日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

Kotlin?this關鍵字的使用實例詳解_Android

作者:破浪會有時 ? 更新時間: 2023-05-19 編程語言

在 Kotlin 中,this 關鍵字允許我們引用一個類的實例,該類的函數恰好正在運行。此外,還有其他方式可以使 this 表達式派上用場。

this可以用來訪問類的成員

我們可以使用 this 作為屬性引用或函數調用的前綴:

class Counter {
    var count = 0
    fun incrementCount() {
        this.count += 2
    }
}

使用 this 作為前綴,我們可以引用類的屬性。 我們可以使用它來解決具有類似名稱的局部變量的歧義。

同樣,我們也可以使用 this 調用成員函數。

使用this訪問類實例

我們可以使用獨立的 this 來表示對象的一個實例:

class Foo {
    var count = 0
    fun incrementCount() {
        incrementFoo(this)
    }
}
private fun incrementFoo(foo: Foo) {
    foo.count += 2
}
fun main() {
    val foo = Foo()
    foo.incrementCount()
    println("Final count = ${foo.count}")
}

這里,this 表示類本身的實例。 例如,我們可以將類實例作為參數傳遞給函數調用。

此外,我們可以使用 this 將實例分配給局部變量。

二級構造函數的委托

在 Kotlin 中,二級構造函數(secondary constructors)必須委托給主構造函數。 我們可以使用 this 來委托:

class Car(val id: String, val type: String) {
    constructor(id: String): this(id, "unknown")
}

這里,Car 的二級構造函數委托給主構造函數。事實上,我們可以在類的主體中定義任意數量的額外的構造函數。

如果this沒有限定符,那么它指向包含當前代碼的最內層范圍.如果想要指向其他范圍內的this,需要使用標簽限定符。

帶限定符的this

為了訪問更外層范圍(比如 類, 或 擴展函數, 或有標簽的 帶接受者的函數字面值)內的 this, 我們使用this@label , 其中的 @label 是一個標簽, 代表我們想要訪問的this所屬的范圍:

class A { // 隱含的標簽 @A
  inner class B { // 隱含的標簽 @B
    fun Int.foo() { // 隱含的標簽 @foo
      val a = this@A // 指向 A 的 this
      val b = this@B // 指向 B 的 this
      val c = this // 指向 foo() 函數的接受者, 一個 Int 值
      val c1 = this@foo // 指向 foo() 函數的接受者, 一個 Int 值
      val funLit = lambda@ fun String.() {
        val d = this // 指向 funLit 的接受者
      }
      val funLit2 = { s: String ->
        // 指向 foo() 函數的接受者, 因為包含當前代碼的 Lambda 表達式沒有接受者
        val d1 = this
      }
    }
  }
}

原文鏈接:https://blog.csdn.net/zyctimes/article/details/127452471

欄目分類
最近更新