Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variables inside a constructor should be private or public in Kotlin

Tags:

android

kotlin

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.

like image 762
SVK Avatar asked Oct 15 '25 13:10

SVK


1 Answers

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
like image 181
aminography Avatar answered Oct 17 '25 11:10

aminography



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!