Is it possible to upcast properties getter type?
For example, inside class declaration I have val member = Implementation()
, but I want for the public getter to return a reference typed with SomeInterface
assuming that Implementation
is a subtype of SomeInterface
, whereas inside the class declaration this type will be used as a Implementation
instance.
Here is a complete example in Java to give a clear picture:
public class MyViewModel extends ViewModel {
private final MutableLiveData<Settings> settings = new MutableLiveData<>();
public LiveData<Settings> getSettings() {
return settings;
}
public void updateSettings() {
settings.setValue(new Settings());
}
}
Here this "property" is visible outside as a LiveData
(supertype of MutableLiveData
), but inside the class it is possible to use it as MutableLiveData
.
I would say it sounds natural, but seems that Kotlin doesn't allow this. Am I missing something? Or creating private val _private = Implementation()
and val _public: SomeInterface = _private
or implementing a custom method with getter semantics and modified name having SomeInterface
return type is the only way to achieve this?