android - 构造函数中的变量在 Kotlin 中应该是私有(private)的或公共(public)的

标签 android kotlin

我想了解构造函数中的变量在 Kotlin 中应该是 private 还是 public
在类构造函数中访问修饰符有什么意义?

在下面的代码 fragment 中,变量servicequeryprivate
保密有什么用?
它有什么帮助?

class GithubPagingSource(
        private val service: GithubService,
        private val query: String
) : PagingSource<Int, Repo>() { 
    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, Repo> {
        TODO("Not yet implemented")
    }
}

注意:我在 Stack overflow 上阅读了多个与此区域相关的问题和答案,但找不到任何有效答案。

最佳答案

需要考虑的是,kotlin 中构造函数的定义不同于 java。在您提供的代码段中,该类有一个主构造函数。根据kotlin docs :

The primary constructor is part of the class header: it goes after the class name (and optional type parameters).

例如:

class GithubPagingSource(
    service: GithubService,
    query: String
)

还有:

Note that parameters of the primary constructor can be used in the initializer blocks. They can also be used in property initializers declared in the class body.

那么,如果我们想在函数体内使用它们,我们应该怎么做呢?

在这种情况下,我们必须通过向主构造函数的参数添加 varval 来声明类属性:

class GithubPagingSource(
    val service: GithubService,
    val query: String
) : PagingSource<Int, Repo>() { 

    init {
        println("$query") // query is accessible here
    }

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, Repo> {
        println("$query") // query also is accessible here
    }
}

现在,servicequery扮演着两个角色:

  • 首先作为构造函数参数
  • 其次作为类变量

另一方面, encapsulation principle 告诉我们尽可能限制类变量。这意味着您应该让它们保持私有(private),除非需要从外部可见。

class GithubPagingSource(
    private val service: GithubService,
    private val query: String
) : PagingSource<Int, Repo>() { 
    ...
}

因此,如果我们有对此类实例的引用:

val githubPagingSource = ...
val query = githubPagingSource.query // is not accessible here

关于android - 构造函数中的变量在 Kotlin 中应该是私有(private)的或公共(public)的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65536510/

相关文章:

android - bluetoothGatt writeCharacteristic 返回 false

Android - 如何使用数据绑定(bind)从 XML 传递 View 对象

string - Kotlin - 如何正确连接字符串

android - 观察 onCreate fragment 时调用的 LiveData

android - 在 Kotlin 中设置 Android 监听器 - 在 lambda 中使用 return

android - 构建 Flutter Android 应用程序时 AppCenter 构建崩溃

android - 动态壁纸也可以是应用程序吗? (应用程序有一个单独的 Activity )

Android MapView 可拖动标记

Android M CDD - 运行时权限要求

class - Kotlin 类中 "this"的用途