在Kotlin中,如何仅通过特定类型访问属性 [英] In Kotlin, how to make a property accessible by only specific type

查看:131
本文介绍了在Kotlin中,如何仅通过特定类型访问属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说我有一个类似的Kotlin课:

Lets say I have a Kotlin class similar to this:

class MyKotlinExample {
    val mMyString = MutableLiveData<String>()
}

MutableLiveData扩展了LiveData,但是我不想将MutableLiveData公开给其他类.他们只能将/c作为我的特殊String

MutableLiveData extends LiveData however I don't want to expose MutableLiveData to other classes. They should only see/access LiveData<String> as my special String

有可能,和/或好的/建议的?

Is it possible, and/or good/advised etc?

推荐答案

您可以使用


您还可以提供到客户端的界面,该界面仅提供LiveData<String>.给定以下类别:


You can also provide an interface to your clients, which provides only LiveData<String>. Given the following classes:

interface LiveData<T> {

    val value: T
}

data class MutableLiveData<T>(override var value: T) : LiveData<T>

创建以下接口/实现:

interface MyExampleInterface {

    val myString: LiveData<String>
}

class MyExampleClass : MyExampleInterface {

    override val myString: MutableLiveData<String> = MutableLiveData("")
}

在内部,您可以将myString作为MutableLiveData进行访问,并且可以将MyExampleClass的实例作为MyExampleInterface进行传递,因此他们只能将myString作为LiveData<String>进行访问.

Internally, you can access myString as MutableLiveData, and you can pass the instance of MyExampleClass as MyExampleInterface so they can only access myString as LiveData<String>.

这篇关于在Kotlin中,如何仅通过特定类型访问属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆