Kotlin Data Class

Kotlin provides facility of data classes. The main purpose of data class is to hold data and it is very simple to create. This can frequently be created without writing a lot of boilerplate code.

Syntax of Data class

data class class_name(parameter1,parameter2,.....parameterN)

Data class is marked with the keyword data. As we show in the above syntax it is defined in a single line and does not contain any additional logic.

Example

data class student(var roll: Int, var name: String, var class: Int, var section: String)

In the above example, we have created a data class student. It is very simple and clear.


Instantiate a data class

We can instantiate a data class in the same way as other classes.

Example

data class student(var roll: Int, var name: String, var className: Int, var section: String)
fun main(args : Array<String>)  { 
    val std = student(101,"Priska",10,"A")
    println(std.roll)
    println(std.name)
    println(std.className)
    println(std.section)
}
Output
101
Priska
10
A

In the above example, we have created a data class student and instantiated in the main method.



Copy Method

We can use the copy method with data classes to create a new instance of your type to change the fields values.

Example

data class student(var roll: Int, var name: String, var className: Int, var section: String)
fun main(args : Array<String>)  { 
    val std = student(101,"Priska",10,"A")
	var std1 = std.copy(102,"Kashyap",20,"B")
	println(std1.roll)
    println(std1.name)
    println(std1.className)
    println(std1.section)
}
Output
102
Kashyap
20
B

Requirements of a data class

A data class has to fulfill the following requirements.

  • The primary constructor needs to have at least one parameter.
  • All primary constructor parameters need to be marked as val or var.
  • Data classes cannot be abstract, open, sealed or inner.
  • Data classes may only implement interfaces.

Data class built-in methods

In kotlin, the compiler automatically created the following members with data class.

  • equals()
  • hashcode()
  • toString()
  • copy()
  • componentN()






Read more articles


General Knowledge



Learn Popular Language