In Kotlin, how to make a property accessible by on

2019-02-24 00:35发布

问题:

Lets say I have a Kotlin class similar to this:

class MyKotlinExample {
    val mMyString = MutableLiveData<String>()
}

MutableLiveData extends LiveData however I don't want to expose MutableLiveData to other classes. They should only see/access LiveData<String> as my special String

Is it possible, and/or good/advised etc?

回答1:

You can use a backing property:

class MyKotlinExample {

    private val _myString = MutableLiveData<String>()
    val myString: LiveData<String>
      get() = _myString
}

You can also provide an interface to your clients, which provides only LiveData<String>. Given the following classes:

interface LiveData<T> {

    val value: T
}

data class MutableLiveData<T>(override var value: T) : LiveData<T>

Create the following interface/implementation:

interface MyExampleInterface {

    val myString: LiveData<String>
}

class MyExampleClass : MyExampleInterface {

    override val myString: MutableLiveData<String> = MutableLiveData("")
}

Internally, you can access myString as MutableLiveData, and you can pass the instance of MyExampleClass as MyExampleInterface so they can only access myString as LiveData<String>.



回答2:

You should use a getter which does the cast for you:

class MyKotlinExample {
    private val mMyString = MutableLiveData<String>()

    fun getNonMutableLiveData(): LiveData<String> = mMyString
}


回答3:

I would make the field private and expose the value like so:

class MyKotlinExample {
    private val mMyString = MutableLiveData<String>()

    fun getMyString(): String = mMyString.getValue()
}


回答4:

This is quite simple - you set the type of the property to LiveData<String>, but initialize it with the instance of MutableLiveData<String>:

class MyKotlinExample {
    val mMyString: LiveData<String> = MutableLiveData<String>()
}