kotlin - Data Class Example

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. In Kotlin, this is called a data class and is marked as data
For example:
data class User(val name: String, val age: Int)
Declaring a data class must contain at least one primary constructor with property argument (val or var).
Data class internally contains the following functions:
  • equals(): Boolean
  • hashCode(): Int
  • toString(): String
  • component() functions corresponding to the properties
  • copy()

Kotlin Data Class Example

package net.javaguides.kotlin.examples

data class User(val name: String, val age: Int)

fun main(args: Array<String>) {
    
 val jack = User("Ramesh", 29)
 
    println("name = ${jack.name}")
    println("age = ${jack.age}")
}
Output:
name = Ramesh
age = 29

Copying Example

package net.javaguides.kotlin.examples

data class User(val name: String, val age: Int)

fun main(args: Array < String > ) {

    val u1 = User("Ramesh", 29)

    // using copy function to create an object
    val u2 = u1.copy(name = "Pramod")
    val u3 = u1.copy()
    println("u1: name = ${u1.name}, name = ${u1.age}")
    println("u2: name = ${u2.name}, name = ${u2.age}")
    println("u3: name = ${u3.name}, name = ${u3.age}")
}
Output:
u1: name = Ramesh, name = 29
u2: name = Pramod, name = 29
u3: name = Ramesh, name = 29

toString() Method Example

package net.javaguides.kotlin.examples

data class User(val name: String, val age: Int)

fun main(args: Array<String>) {

 val user = User("Ramesh", 29)
 println(user.toString());
}
Output:
User(name=Ramesh, age=29)

Comments