Home > OS >  What will happen if I convert the existing data class to nor class in kotlin
What will happen if I convert the existing data class to nor class in kotlin

Time:09-07

What will happen if I convert the existing data class to nor class in kotlin

Will it break the functionality because we are using data and suddenly we are converting to normal class

CodePudding user response:

While converting data class to normal class, core functionalities will not break.

But you need to make sure several things. Data class has its own implementation of default methods like toString() , equals() and hashCode().

So if you using any of these in your code, you should make sure to override implementation in normal class.

Here is an example of checking equals.

    var a = Foo("abc")
    var b = Foo("abc")
    println(a == b) //True
    var a1 = Bar("abc")
    var b1 = Bar("abc")
    println(a1 == b1) //False

data class Foo(var a: String)

class Bar(var a: String)

So here since data class has its own implemenation of equals using hashcode of all the fields, if the values of fields inside object is similar it returns true. But it in normal class since equals and hascode is not overridden, it will return false. You need to override them based on your requirement.

Hope it helps.

Thanks Tenfour04 for your good point. Here is an example using a map. In data class it will replace existing entry as old object will be equal to new object. But in normal class it will add as new entry as both object are different. Same thing would apply to set.

var map = hashMapOf<Foo,Int>(Foo("abc") to 2,Foo("abc") to 3)
println(map) //{Foo(a=abc)=3}
var map1 = hashMapOf<Bar,Int>(Bar("abc") to 2,Bar("abc") to 3)
println(map1) //{Bar(a = abc)=3, Bar(a = abc)=2}

class Bar(var a: String){
    override fun toString():String = "Bar(a = $a)" 
}

Playground Link

  • Related