Monday 12 February 2018

Kotlin: Data classes

Data classes are special kind of classes in kotlin, their main purpose is to hold the data.

Kotlin derives below members for the data classes.

a.   equals()/hashCode() pair
b.   toString() of the form "User(name=John, age=42)"
c.   componentN() functions corresponding to the properties in their order of declaration
d.   copy().

How to define data class?
By using the keyword ‘data’ we can define data classes.

Syntax
data class ClassName(memberVariables)

Ex
data class Employee(var firstName: String, var lastName: String, var id: Int)

Find the below working application.

Test.kt
package com.sample.test

data class Employee(var firstName: String, var lastName: String, var id: Int)

fun main(args: Array<String>) {
 var obj = Employee("Krishna", "Gurram", 1)

 var firstName = obj.firstName;
 var lastName = obj.lastName
 var id = obj.id

 println("First Name : $firstName")
 println("Last Name : $lastName")
 println("Id : $id")

}

Output

First Name : Krishna
Last Name : Gurram
Id : 1

Is there any constraints while defining data classes?
Yes, below constraint are applied while defining data classes.

a.   The primary constructor needs to have at least one parameter
b.   All primary constructor parameters need to be marked as val or var
c.   Data classes cannot be abstract, open, sealed or inner

d.   Data classes may only implement interfaces.






Previous                                                 Next                                                 Home

No comments:

Post a Comment