Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for The potential traps in Kotlin's Data Classes
Dan Newton
Dan Newton

Posted on • Originally published atlankydan.dev on

     

The potential traps in Kotlin's Data Classes

The aim of this post is not to point out some massive flaws in Kotlin’s design of data classes and show you how to get passed them. Actually, it is quite the opposite. The contents of this post are clearly documented in theKotlin docs. I am merely here to highlight this information to anyone who has not noticed precisely how their data classes are working.

Data classes are convenient for us developers, especially those of us coming over from Java. They provide several generated functions allowing you to write a fully functional class with very little code. Data classes provide the following generated functions:

All of the above are generated for properties defined in a class’ primary constructor. Anything defined outside of this constructor is ignored. This is the potentialtrap. But, this is only a trap if you are not aware of how data classes work. As I mentioned earlier, it is clearlydocumented, you only need to be mindful of it. Which you now are, of course.

If you are not considerate in how you define your data classes, you are likely to find some bugs in your application.equals andhashCode are generally essential functions. If they do not work as expected, bugs are sure to follow.

Below is an example of this:

data classMyClass(vala:String,valb:Int){// property defined outside of primary constructorlateinitvarc:String}funmain(){// create two equal objectsvalmyClass=MyClass("abc",0)valmyClass2=myClass.copy()// check their hashCodes are the same and that they equal each otherprintln("myClass hashCode: ${myClass.hashCode()}")println("myClass2 hashCode: ${myClass2.hashCode()}")println("myClass == myClass2: ${myClass == myClass2}")// set the lateinit variablesmyClass.c="im a lateinit var"myClass2.c="i have a different value"// have their hashCodes changed?println("myClass hashCode after setting lateinit var: ${myClass.hashCode()}")println("myClass2 hashCode after setting lateinit var: ${myClass2.hashCode()}")// are they still equal to each other?println("myClass == myClass2 after setting lateinit vars: ${myClass == myClass2}")// sanity check to make sure I'm not being stupidprintln("sanity checking myClass.c: ${myClass.c}")println("sanity checking myClass2.c: ${myClass2.c}")}
Enter fullscreen modeExit fullscreen mode

Executing this example outputs:

myClasshashCode:2986974myClass2hashCode:2986974myClass==myClass2:truemyClasshashCodeaftersettinglateinitvar:2986974myClass2hashCodeaftersettinglateinitvar:2986974myClass==myClass2aftersettinglateinitvars:truesanitycheckingmyClass.c:imalateinitvarsanitycheckingmyClass2.c:ihaveadifferentvalue
Enter fullscreen modeExit fullscreen mode

As you can see thehashCode of each object is the same, and they are both equal to each other, even though theirc properties are different. If you tried to make use ofMyClass inside of aMap orSet, the chance of entries colliding with each other increases. That being said, it really does depend on what you are trying to achieve. Maybe this is precisely what you want to happen. In which case, more power to you.

Placingc into theMyClass constructor would affect thehashCode andequals implementation.c would then be involved in any calls tohashCode,equals and the rest of the generated functions.

If you haven’t done so already, I recommend that you take a quick look at thedocumentation on this subject. Highlighting this information was the goal of this post. It’s not some fancy code that does something magical. Instead, it is something more basic and fundamental to how Kotlin works. Being aware of how data classes work in this aspect can be vital to reducing the number of bugs in your application.

If you enjoyed this post or found it helpful (or both) then please feel free to follow me on Twitter at@LankyDanDev and remember to share with anyone else who might find this useful!

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

I write tutorials on my blog at www.lankydan.dev . During the day, I am a Platform Engineer at r3 where I work on Corda, an Open Source DLT/Blockchain Platform.
  • Location
    Reading
  • Education
    University of Leicester
  • Work
    Staff Software Engineer at R3
  • Joined

More fromDan Newton

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp