是否可以更改 Kotlin 的 属性 getter 类型?

Is it possible to change Kotlin's property getter type?

是否可以向上转换属性 getter 类型?

例如,在 class 声明中我有 val member = Implementation(),但我想要 public getter return 类型为 SomeInterface 的引用,假设 ImplementationSomeInterface 的子类型,而在 class 声明中,此类型将用作 Implementation实例。

下面是Java中的完整示例,以提供清晰的图片:

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());
    }
}

这里 "property" 在外部可见为 LiveDataMutableLiveData 的超类型),但在 class 内部可以将其用作 MutableLiveData.

我会说这听起来很自然,但似乎 Kotlin 不允许这样做。我错过了什么吗?或者创建 private val _private = Implementation()val _public: SomeInterface = _private 或实现具有 getter 语义的自定义方法和具有 SomeInterface return 类型的修改名称是实现此目的的唯一方法?

我认为(如果我正确理解了你的问题)显式声明 member 的类型会做你想做的,例如

interface SomeInterface

class Implementation : SomeInterface

class Test {
    val member: SomeInterface = Implementation()
}

UPDATE:问题更新后澄清在测试中 class member 应该是 Implementation 类型,而不是 [=15] =]...

我不认为没有成员变量就可以完成你想做的事情,正如你在问题中所建议的那样。然而,如果你有一个基础 class 定义了你的 member 应该是什么,你 可以 做你想做的事:

interface SomeInterface

class Implementation : SomeInterface

abstract class Super {
    abstract val member: SomeInterface
}

class Test : Super() {
    override val member = Implementation()  
    // declared as Implementation, but does correctly implement superclass which wants this to be a SomeInterface.
    // In this class, member is of type Implementation.
}

fun test() {
    val test1 = Test()
    val member1 = test1.member  // member1 is an Implementation object

    val test2: Super = Test()
    val member2 = test2.member  // member2 is a SomeInterface object
}

上面显示的是,您可以拥有一个 member,它在您的 class 中作为 Implementation 可用,但在 class 之外作为 SomeInterface。但前提是,当你在 class 之外使用它时,你将它作为 superclass 的一个实例来使用,它定义 member 为类型 [=15] =].