I am seeing the following error
Platform declaration clash: The following declarations have the same JVM signature (getHosts()Landroidx/lifecycle/MutableLiveData;): private final fun
<get-hosts>
(): MutableLiveData<List> defined in com.example.xx.viewmodel.HostsViewModel public final fun getHosts(): MutableLiveData<List> defined in com.example.xx.viewmodel.HostsViewModel
What am I doing wrong?
class HostsViewModel : ViewModel() {
private val hostsService = HostsService()
private val hosts: MutableLiveData<List<Host>> by lazy {
MutableLiveData<List<Host>>().also {
loadHosts()
}
}
fun getHosts(): MutableLiveData<List<Host>> {
return hosts
}
private fun loadHosts(){
hosts.value = hostsService.getHosts().body()
}
}
CodePudding user response:
For every class property (val
), Kotlin generates a getter called getHosts()
and for var
also a setter called setHosts(MutableLiveData<List<Host>> value)
as per Java's convention. It hides it from the Kotlin user as getters and setters are usually just boilerplate code without offering much value. As such, your own getHosts()
method clashes with the generated method at compilation. You have multiple possibilities to solve this issue:
- Rename
private val hosts
to something else, e.g.private val internalHosts
- Annotate the
getHosts
method with@JvmName("getHosts2")
. If you do that though, consider the possibility that someone might call your code from Java and in that case, the caller would need to callgetHosts2()
in Java code, which might not be such nice API-design. - Reconsider your api design. In your case, you could simply make
val hosts
public and remove yourgetHosts()
entirely, as the compiler will auto-generategetHosts()
for you.
In addition to that, you might want to consider not exposing MutableLiveData
in general as mentioned in the comments.
Edit:
Also, I would recommend that you do this:
val hosts: MutableLiveData<List<Host>> by lazy {
MutableLiveData<List<Host>>().also {
it.value = hostsService.getHosts().body()
}
}
and remove loadHosts
to make your code more concise.