The thing to consider is that definition of constructors in kotlin is different than java. In your provided snippet, the class has a primary constructor. According to the kotlin docs:
The primary constructor is part of the class header: it goes after the class name (and optional type parameters).
For example:
class GithubPagingSource(
service: GithubService,
query: String
)
also:
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.
So, what should we do if we want to use them inside the body of a function?
In this case, we have to declare class properties by adding var or val to the parameters of the primary constructor:
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
}
}
Now, service and query are playing two roles:
- first as constructor parameters
- second as class variables
On the other hand, the encapsulation principle tells us to keep class variables as much restricted as possible. It means that you should keep them private unless there is a need to be visible from outside.
class GithubPagingSource(
private val service: GithubService,
private val query: String
) : PagingSource<Int, Repo>() {
...
}
So, if we have a reference to an instance of this class:
val githubPagingSource = ...
val query = githubPagingSource.query // is not accessible here