Data Classes

5 0 0
                                        

data class - a class whose sole function is just to hold data. The data keyword precedes the class keyword. 

syntax:

data class Name(val param1: Type)

Rules:

1. It needs to have at least one parameter that is marked by either val or var.

2. It should not be abstract, sealed, inner or open.

3. The inherited function from the Mother of all Mother class would be useful which are equals(), hashcode(), toString(), componentN() and copy(). But you are not allowed to modify the componentN() and copy() function. The componentN() refers to parameter in the primary constructor. It is like calling parameter1 as component1.

4. These autogenerated function are only applicable in the primary constructor. The properties you created inside the data class body will be treated differently. So, if you create an object with the same arguments in the primary constructor but with different property values in the data body, they will be treated as equal.

================

fun main(){

    val m1 = Music("Man up", "Haile Steinfield")

    val m2 = m1.copy(title = "Your name hurts")

     displaySomething(m1, m2)

     val (x, y) = m1

     println(Song $x is sung by $y)

}

data class FavouriteMusic(var title: String = "2002", var artist: String = "Anne Marie")

fun displaySomething(d1: Any?, d2: Any? = Music()){

    println(d1.toString())

    val id1 = d1.hashCode()

    val id2 = d2.hashCode()

    if(id1.equals(id2)){

        println("$id1 == $id2")

    }else {

        println("$id1 != $id2")

    }

}

================

Result:

Music(title=Man up, artist: Haile Steinfield)

-749329799 != 32850438

Song Man up is sung by Haile Steinfield

Note: I just changed the hashcode for each id just to be safe but it is better to be safe than sorry.


Destructuring declaration  - this is like assigning each component of the data class you created to each variable. The number of components and the number of variables you declared must be the same.

sample:

val m1 = Music()

val (x, y) = m1

println(Song $x is sung by $y)

Kotlin ProgrammingWhere stories live. Discover now