簡體   English   中英

為什么Intent構造函數在伴隨對象中不可見? 科特林

[英]Why Intent constructor is invisible in companion object? Kotlin

class MainActivity : AppCompatActivity() {

    companion object {
        fun makeIntent(pos : Int) {
            println("${pos} is here!")
            var intent = Intent(this, DetailActivity::class.java)
            if (intent != null) {
                println("intent is not null in makeIntent function")
            }   else {
                println("intent is null in makeIntent function")
            }
        }
    }

    ... 
}

在執行var intent = Intent(...)時,看不到Intent。 為什么?

Intent構造函數需要將Context作為參數傳遞。 makeIntent內部, this是對伴隨對象實例的引用。 伴隨對象沒有對包含類的實例的引用。 因此,您必須以某種方式傳遞Context例如:

class MainActivity : AppCompatActivity() {
    companion object {
        fun makeIntent(pos : Int, context:Context):Intent {
            println("${pos} is here!")
            var intent = Intent(context, DetailActivity::class.java)
            return intent
    }
}

除了@meinsol的出色答案之外,如果在makeIntent函數中添加接收器,則可以使代碼幾乎相同:

class MainActivity : AppCompatActivity() {

    companion object {
        fun Context.makeIntent(pos : Int) {  // <- Notice the Context receiver here
            println("${pos} is here!")
            var intent = Intent(this, DetailActivity::class.java)
            // Do what you want with the intent
        }
    }

    ... 
}

然后,您可以在上下文中的任何地方調用它( makeIntent(5) ),或者如果您不在上下文中但有可用的話,請使用它( context.makeIntent(5)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM