我想了解构造函数中的变量在 Kotlin 中应该是 private 还是 public。
在类构造函数中访问修饰符有什么意义?
在下面的代码 fragment 中,变量service 和query 是private。
保密有什么用?
它有什么帮助?
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.
那么,如果我们想在函数体内使用它们,我们应该怎么做呢?
在这种情况下,我们必须通过向主构造函数的参数添加 var
或 val
来声明类属性:
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
}
}
现在,service
和query
扮演着两个角色:
- 首先作为构造函数参数
- 其次作为类变量
另一方面, 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/