Left Index

Kotlin Data Class

A data class is a class that only contains state and does not perform any operation. We frequently create classes whose main purpose is to hold data. In such a class some standard functionality and utility functions are often mechanically derivable from the data.


The compiler automatically derives the following members from all properties declared in the primary constructor:

Create data class
data class Person(var name: String, var age: Int, var salary: Float)
Data class gives
  • The properties declared in the constructor: this technically is not exclusive to a data class, but it avoids all the boilerplate of getters and setters, in addition to the constructor.
  • equals() / hashCode()
  • componentN() functions corresponding to the properties in their order of declaration
  • A copy()method, very useful when we use immutable objects.
  • toString() of the form

Example:
package com.theitbulls.kotlinex

fun main(args: Array<String>) {
	val person = Person("John", 35, 80000f)
	println("Name: ${person.name}, age: ${person.age}, salary: ${person.salary}")
	
	println(person.toString())
	
	
	println()
	val person1 = person.copy()
	println(person1.toString())
}

data class Person(var name: String, var age: Int, var salary: Float)
Output:
Name: John, age: 35, salary: 80000.0
Person(name=John, age=35, salary=80000.0)

Person(name=John, age=35, salary=80000.0)