dev90
dev90

Reputation: 7519

Unable to access static variable in some other activity class

I have an activity MainACtivity.kt, and i created a companion object like following to create static variable.

   companion object {
        var myStr:String?= null
    } 

Now i want to use myStr in some activity, but its saying that myStr has private access

I am accessing it like following.

class SecondActivity: BaseActivity{

 MainActivity.myStr // myStr has private access

}

Upvotes: 0

Views: 63

Answers (1)

leonardkraemer
leonardkraemer

Reputation: 6783

The error message is quite clear, it says Execting member declaration. Once you actually declare a member it works just fine:

class MainActivity() {
    companion object {
        var myStr: String? = null
    }
}

class SecondActivity {
    val notPrivate = MainActivity.myStr

    //otherwise you can declare a function to access myStr. It just does not work directly inside a class or a file. 
    fun bar(){
        MainActivity.myStr = "i'm not private either"
    }    
}

Upvotes: 1

Related Questions