I would like to understand whether variables inside a constructor should be private or public in Kotlin.
What is the significance of having access to modifiers inside the class constructor?
In the below code snippet, the variable service and query are private.
What is the use of keeping them private?
How does it help?
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")
}
}
Note: I have read multiple questions and answers related to this area on Stack overflow but could not find any valid answer.
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:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With