0
votes

I am fairly new at kotlin. I know concepts of static member in java. According to documentation object works like static class / singleton but i cant seem to access them from my MainActivity. From examples, in kotlin i suppose do it as below but it seems not to be working for me. I am doing it wrong? I want to use object instead of companion object

TAG.kt

object TAG {
    var MainActivity : String? = null
}

MainActivity.kt

class MainActivity : AppCompatActivity(){  
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        //Cannot find TAG.MainActivity as static variable like in Java
        TAG.MainActivity = MainActivity::class.java.canonicalName as String
    }
}

I have seen this posts but not working Static variables in kotlin?

3

3 Answers

3
votes

Perhaps there is a TAG field/property somewhere else in your class? Is TAG imported properly?

This simple Kotlin program works with no errors:

object Obj {
  var Hello = "World"
}

fun main(args: Array<String>) {
  println(Obj.Hello)
}

Prints:

World
3
votes

Put the required object inside Companion Object whereas, it works like static in Kotlin

class MyClassWithStatics {
    companion object {
        const val SOME_CONSTANT = "Hello!"

        @JvmField var someUglyMutableField: String = "don't do this like ever"

        @JvmStatic fun hello() { println("$SOME_CONSTANT $someUglyMutableField") }
    }
}
// consuming Java code!
public class MyOtherClass {
    public void doSomething() {
        String constant = MyClassWithStatics.SOME_CONSTANT;
        String someUglyMutableField = MyClassWithStatics.someUglyMutableField;
        MyClassWithStatics.hello();
    }
}

Also, check this out to handle issue while accessing static object in Kotlin class https://kotlinlang.org/docs/tutorials/kotlin-for-py/objects-and-companion-objects.html

2
votes

-----------UPDATED ANSWER----------

OP wants to have a top-level TAG object. The code OP provided in the question is actually correct.
The issue was that OP's Android Studio needed a restart.

----------MY ORIGINAL ANSWER (but still good for reference)----------

Putting it in a companion object is an option.

class MainActivity : AppCompatActivity() {  

    //You can name this object here too (like "companion object shared")
    companion object {
        var TAG: String? = null
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        //Notice the ordering here. In fact, you don't even have to type MainActivity. You can just type TAG = ...
        MainActivity.TAG = MainActivity::class.java.canonicalName as String
    }
}