Override getter for Kotlin data class

Data class is a collection in Kotlin to store data. Logically this is same as creating a Java POJO class. In Java, we do create extra member functions to set and get the data in the member variables. In Kotlin, we don’t need to create separate methods to access the member variables of the class. Kotlin provides it by default. We can access the variables by just using the member variable names in it.

  • It is not recommended to override any of the data class members like we used to do in Java.

  • It is always recommended to use normal class if you want to override any of the class member at the runtime.

  • As a programmer, we need to keep in mind that Data class is made for holding the data, not for modifying the same at runtime.

Kotlin data classes reduce the boilerplate code and provide the common functions such as getter, setters, toString, equals, etc. automatically. In this article, we will see how we can override a normal class function which is used to fetch the data.

Override function in Kotlin

In this example, we will see how to override the value of the integer variable in a Data class when the value of the same is negative.

We have one Data class "myClass" and we have one data member "myValue". We will override the value using the function getValue().


fun main() {
   println(myClass(5).getValue()) // will print 5

   // it won't be printing -5
   // instead we will get 0 as per our logic

data class myClass(private val myValue: Int) {
   // overriding the value
   fun getValue(): Int = if (myValue < 0) 0 else myValue


When you execute the code, it will produce the following output −