The preferred private modifier is the most restrictive modifier. When the properties are declared with private access, they are not accessible from outside the class:
private var name : String
Let's take an example of the Person class and apply the private visibility modifier:
class Person(pName: String, pAge: Int, pHeight : Double ) {
private var name : String = pName
private var age : Int = pAge
private var height : Double = pHeight
init {
require(name.trim().isNotEmpty()) {"Name should not empty"}
require(age > 0 ) {"Age is not correct"}
require(height > 0) {"Height is not correct"}
}
}
fun main(args: Array<String>) {
val person = Person("bob",40,6.1)
println("Name ${person.name}, Age ${person.age} Height ${person.height}"
}
As soon as we implement the private modifier on each property of the Person class, the Kotlin compiler throws the following error in the main function:
Cannot access 'property name': it is private in 'Class name'
The only way to access the private properties is to add our own functions. Write the getAge function to read the age property and the setAge function to update it. In the previous section, we mentioned that one of the disadvantages of having direct access is that we cannot protect our properties from unwanted values:
person.age = -41
person.height = 20.0
By assigning the private visibility modifier to the age or height properties, we are not permitted to access them directly. Let's add the getAge and setAge functions to read and write the age property:
class Person(pName: String, pAge: Int, pHeight : Double ) {
private var name : String = pName
private var age : Int = pAge
private var height : Double = pHeight
init {
require(name.trim().isNotEmpty()) {"Name should not empty"}
require(age > 0 ) {"Age is not correct"}
require(height > 0) {"Height is not correct"}
}
fun getAge() : Int{
return age;
}
fun setAge(age : Int) {
require(age > 0 ) {"Age is not correct"}
this.age = age
}
fun display(){
println("Name ${name}, Age ${age} Height ${height}")
}
}
fun main(args: Array<String>) {
val person = Person("bob",40,6.1)
person.display()
person.setAge(42)
person.display()
}
Now, if we need to update a property, we can verify it beforehand. The setAge function verifies the age before assigning it to the age property.
Similarly, we are required to add the display function within the class to print the class properties on the screen because all properties are declared as private and cannot access person.age or person.name in the main function.