Kotlin: Private Properties and Methods

Recently I wrote about the frustration I had with private fields, properties and methods in Groovy/Grails (or the lack thereof.) For reference, that article is linked below:

Kotlin behaves like Groovy in some regards, and like Java in others. Like Groovy, Kotlin has implicit getters and setters.

class Animal {
    var age: Int = 0                   
    private var name: String = "Tim"    
    val legs: Int = 2                   
}

fun main(args: Array<String>) {
    val animal = Animal()
    animal.age = 8
    println(animal.age)
}

Above, the age variable has getters and setters behind it. They do not need to be specified in the code (unlike Java.) So in the main function, we can instantiate the Animal class and then call the age and set it to a new value, or print it out.

HOWEVER, unlike Groovy, if we park a property as “private” it can not be accessed at all – as in many other programing languages. Groovy tricks many developers into thinking that they have successfully encapsulated the data or method because they used the private keyword – and I met a Senior Java dev just the other day who though THIS EXACT thing. He was shocked when I showed him that even though his property was PRIVATE, I could instantiate the class and overwrite it. Crazy!

Another Kotlin specific feature, is that any variable that is immutable (such as the legs one above) it has getters generated under the hood, BUT NOT setters. This is because the val keyword sets the variable as immutable.

Leave a Reply

Your email address will not be published. Required fields are marked *