Search code examples
kotlinvalue-typedata-classreference-type

Are Kotlin data classes Value types or Reference type?


I am from Swift background. Swift has both "value" type & "reference" type support, I am bit curious. Does Kotlin have similar concepts?

By default, any class is a reference type. Whereas, with some digging, I found "data class" in Kotlin behaves as a value type.

I don't have clarity from official documentation. https://kotlinlang.org/docs/data-classes.html

Can some one please help in understanding this concept?


Solution

  • Data classes in Kotlin don't differ that much from regular classes. They are represented and passed as a reference to an object on the heap.

    Kotlin has a limited support for value/inline classes:

    value class Password(private val s: String)
    

    Unfortunately, as for now this is restricted to only a single field per class.

    You can find more information in the KEEP, including reasoning on whether to support multiple fields before/after the Project Valhalla: https://github.com/Kotlin/KEEP/blob/master/notes/value-classes.md