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?
Kotlin will generate a backing field for a property if we use at least one default accessor or we reference the field identifier inside a custom accessor. Default accessors are those that are generated with val or var keywords.
Properties. Properties are the variables (to be more precise, member variables) that are declared inside a class but outside the method. Kotlin properties can be declared either as mutable using the “var” keyword or as immutable using the “val” keyword. By default, all properties and functions in Kotlin are public.
In Kotlin both the header and the body are optional; if the class has no body, curly braces can be omitted.
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>
.
You should use a getter which does the cast for you:
class MyKotlinExample {
private val mMyString = MutableLiveData<String>()
fun getNonMutableLiveData(): LiveData<String> = mMyString
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With