ant2009
ant2009

Reputation: 22486

Return the type of a extended class give platform declaration clash

I have the following declaration:

val selectedPhotos: MutableLiveData<List<Photo>> = MutableLiveData()

I have the following method that should return the selectedPhotos which is a MutableLiveData type.

fun getSelectedPhotos(): MutableLiveData<List<Photo>> {
    return selectedPhotos
}

However, the following give me an error:

Platform declaration clash: The following declarations have the same JVM signature (getSelectedPhotos()Landroidx/lifecycle/MutableLiveData;):
    fun <get-selectedPhotos>(): MutableLiveData<List<Photo>> defined in com.raywenderlich.android.combinestagram.SharedViewModel
    fun getSelectedPhotos(): MutableLiveData<List<Photo>> defined in com.raywenderlich.android.combinestagram.SharedViewModel

However, If I change the fun to return the following everything works ok:

fun getSelectedPhotos(): LiveData<List<Photo>> {
    return selectedPhotos
}

However, looking at the following MutableLiveData extends LiveData

public class MutableLiveData<T> extends LiveData<T> {
...
}

Just confused about why I can't use MutableLiveData as the return type which is the correct type that I have declared.

Many thanks in advance,

Upvotes: 0

Views: 94

Answers (1)

Ashok
Ashok

Reputation: 2706

When you declare something in kotlin, the kotlin creates it's setter and getter for you. So considering you declare var abc, kotlin will declare setAbc and getAbc, which is very handful for data classes.

In your case since your property name is selectedPhotos, kotlin would have already created a getter with name getSelectedPhotos with return type MutableLiveData>. Due to this, you are getting clash as two methods have same name and return type.

In your case, you don't need to declare this getSelectedPhotos explicitly, as the kotlin has already declared that for you. You can access that getter and setter declared by kotlin in both kotlin and JAVA class.

Edit: In case, you want to look into the generated JAVA class for your kotlin file, open your kotlin file and then go to Tools -> Kotlin -> Show Kotlin Bytecode and then click on Decomplie button present on opened screen.

Upvotes: 2

Related Questions