Kotlin教程

kotlin更多语言结构——>This表达式

本文主要是介绍kotlin更多语言结构——>This表达式,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

This表达式

  为了表示当前的 接收者 我们使用 this 表达式:

  — 在类的成员中,this指的是该类的当前对象。
  — 在扩展函数或者带有接收者的函数字面值中,this 表示在点左侧传递的 接收者 参数。

  如果 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
            }
        }
    }
}

 

Implicit this

  当对 this 调用成员函数时,可以省略 this. 部分。但是如果有一个同名的非成员函数时,请谨慎使用,因为 在某些情况下会调用同名的非成员

fun printLine() { println("Top-level function") }

class A {
    fun printLine() { println("Member function") }

    fun invokePrintLine(omitThis: Boolean = false) {
        if (omitThis) printLine()
        else this.printLine()
    }
}

A().invokePrintLine() // Member function
A().invokePrintLine(omitThis = true) // Top-level function

 

 

 

 

 

 

 

 

这篇关于kotlin更多语言结构——>This表达式的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!