Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Kotlin, how to make a property accessible by only specific type

Tags:

android

kotlin

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?

like image 459
guness Avatar asked Aug 07 '17 14:08

guness


People also ask

What is backing property in Kotlin?

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.

What are Kotlin's properties?

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.

Can you declare a class without a body in Kotlin?

In Kotlin both the header and the body are optional; if the class has no body, curly braces can be omitted.


2 Answers

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>.

like image 176
nhaarman Avatar answered Oct 26 '22 04:10

nhaarman


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

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

    fun getNonMutableLiveData(): LiveData<String> = mMyString
}
like image 1
Willi Mentzel Avatar answered Oct 26 '22 03:10

Willi Mentzel