Data classes

A new thing Kotlin introduces over many other languages like Java is the data class. In Java (and many other languages) we often make a class with

  • getters - read data
  • setters - change the value of data
  • toString() - convert the object to a string
  • toHashCode() - get a numeric unique value representing the object
  • equals() - check if two objects are equal
  • copy() - copy objects

This is often 20-30 lines of template code added to the start of almost every class and often copy pasted or generated by an IDE. Long and similar looking repetitive code can often lead to bugs so Kotlin offers a way of avoiding the problem entirely by just adding one word data before the start of a class.

data class Hero(val name: String, val type: String, var healthPoints: Int) {

Just adding that lets us do a lot.

Creating Objects

Creating objects is the same as normally dealing with classes in Kotlin.

The generated toString() gives a pretty good default print that is useful for debugging.

val hero1 = Hero("Harsh", "Mage", 100)
println(hero1) // get a nice print
// => Hero(name=Harsh, type=Mage, healthPoints=100)

Getters and Setters

You can access variables via the dot .variableName notation. To set things you use the .variableName = syntax.

println(hero1.healthPoints) // get values
// => 100
hero1.healthPoints = 80 // set values (var only)
// => Hero(name=Harsh, type=Mage, healthPoints=80)


Kotlin sets up things nicely that == works for comparing object’s values.

val hero2 = Hero("Amirtha", "Warrior", 100)
println(hero1 == hero2) // => false
val hero3 = Hero("Harsh", "Mage", 80)
println(hero1 == hero3) // => true

In a lot of other languages == will only compare the reference of the object, that is if they’re the same in memory but not by values. Often that’s not what we really want because that just means checking two variables are the same, so in Java you’d have to create an equals() function to actually compare the object’s values.


Using comma seperated multiple declaration we can extract variables out of an object very easily.

val (name, type, hp) = hero2
println(name) // => Amirtha


Kotlin also makes it really nice to copy over variables and even change a few values.

val mageVarshini = hero2.copy(type = "Mage")
// => Hero(name=Varshini, type=Mage, healthPoints=100)

See More