简体   繁体   中英

How to return different type for a getter property in kotlin

I am trying to return a different type from a getter of a cretin filed.

private val _isDeviceConnectedToTheInernet = MutableLiveData<Boolean>()
val isDeviceConnectedToTheInernet : LiveData<Boolean>
get() =_isDeviceConnectedToTheInernet.value

but kotlin's compiler telling me that "getter return type must be equal to the type of the property" so is there an option to return value of a different type, or i should just write new function to get it's type?

The getter should return _isDeviceConnectedToTheInternet ,without the .value .

private val _isDeviceConnectedToTheInernet = MutableLiveData<Boolean>()
val isDeviceConnectedToTheInernet : LiveData<Boolean>
    get() =_isDeviceConnectedToTheInernet

Option 2:

private val _isDeviceConnectedToTheInernet = MutableLiveData<Boolean>()
val isDeviceConnectedToTheInernet : Boolean?
    get() =_isDeviceConnectedToTheInernet.value

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM