2

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?

1
  • 1
    The difference between data classes and other classes is only a few automatically generated methods like toString, equals etc. In all other respects data class is just a regular class. Commented Apr 3, 2023 at 5:04

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.