Search code examples
androidkotlinandroid-livedataobserversmutablelivedata

Why are MutableLiveData variables declared with equals sign (=)?


In Kotlin, when declaring the type of variable, a colon is used. Even when declaring LiveData, a colon is used. So why is an equals sign used for MutableLiveData? I haven't been able to figure this out. I spent about 2 hours a few days ago trying to understand why my MutableLiveData variable wasn't working only to realize I needed an equals instead of a colon.

Example:

private val _liveData = MutableLiveData<Int>()  
val liveData: LiveData<Int>

Thanks in advance!


Solution

  • Kotlin auto detects the type, so you do not need to specify it. These are equivalent

    val foo: Int = 123
    val foo = 123
    

    However, if you have a variable that is initialized later, you must provide the type, as otherwise the compiler can't determine what type it is. For instance,

    class MyClass {
        val foo: Int  // must specify type
    
        init {
            foo = /* compute foo */
        }
    }
    

    It has nothing to do with LiveData or MutableLiveData.