What is the difference between Kotlin data class and Scala case class?

Asked

Viewed 441 times

6

In Scala we have case classes, for example:

case class Pessoa(nome: String, sobrenome: String)

and in Kotlin we have data classes:

data class Pessoa( val nome: String, val sobrenome: String )

What’s the difference between the two?

  • 2

    Did the answer solve what you were looking to know? Do you think you can accept it now? If not, you need something else to be improved?

1 answer

7

Essentially they are used for the same goal, that is, they define a record. Therefore they automatically gain the main methods necessary, among them the "accessors" methods for the fields, the equality ones, hash code, textual representation (toString) and copy.

Scala also provides methods for apply() and unapply() to the case classes.

In Kotlin, in the data classes, methods are provided that help the selection of patterns similarly to unapply(), though less powerful, language does not require the existence of the apply(). It also has Java Beans "accessors" methods, in addition to the standard ones that are available for any class in Kotlin. Cannot use inheritance in records. It requires the use of var or val for the parameters to indicate which are fields.

Java in newer versions has a similar mechanism called record.

  • One interesting thing about Scala is the method copy also.

  • https://en.wikipedia.org/wiki/Algebraic_data_type, other topic than Scala case class are based (do not know about Kotlin).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.