Kotlin: Unresolved Reference for variable from instantiated class

I make an ear training app and want the levels to be customizable. So I have a class with the same function for each of the 12 tones, so imagine setDb, setD, setEb etc.:

class MakeLevel(context: Context) {
    fun setC(something: Boolean): Boolean {
        var c = something
        return c
    }

I then instantiate the class in my main activity (FullscreenActivity):

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_fullscreen)
    makeLevel = MakeLevel(this)
}
companion object {
    lateinit var makeLevel: MakeLevel
}

Then in the fragment where the levels are selected, I do this:

override fun onResume() {
    super.onResume()
    majpentlevelbutton.setOnClickListener { view ->
        FullscreenActivity.makeLevel.setC(true)
        // [same for setD, setE, setG and setA, and false for all the other notes]
        view.findNavController().navigate(R.id.action_levelSelectFragment_to_chromaticFragment)
    }
}

Now here comes my problem: I want to access the value of c to determine whether ther sounds and the button for c should be loaded or not, and I can´t find a way to do so. For example, I´d like to use it like this:

if (c == true) {
    c_button.visibility = View.VISIBLE
}
else {
    c_button.visibility = View.GONE
}

I´ve tried c, makeLevel.c, FullscreenActivity.makeLevel.c and many more. Every time I get an Unresolved reference. So my question is how do I get a reference on the var c?

2 answers

  • answered 2019-02-10 12:45 Rene

    So far c is only a local variable within the method setC. If you need the value outside of the method you need to define a property:

    class MakeLevel(context: Context) {
        var c = initValue
        fun setC(something: Boolean){
            c = something
        }
    }
    

    Now you can access this variable with: FullscreenActivity.makeLevel.c

  • answered 2019-02-10 13:02 BitcoinKing

    Your problem is that you are trying to access a variable outside of its scope.

    class MakeLevel(context: Context) {
        private var c = initValue
    
        fun setC(something: Boolean){
            c = something
        }
    
        fun getC(something: Boolean) {
            return c
        }
    
        if (getC() == true) 
            c_button.visibility = View.VISIBLE
        else 
           c_button.visibility = View.GONE
    }