Data Classes with Other Properties
You are welcome to have other properties in your data classes, beyond those in the constructor:
data class Animal(val species: String, val ageInYears: Float) {
var isFriendly = true
var isHungry = true
val isCommonlySeenFlyingInTornadoes = false
}
However, code-generated functions, like equals()
and copy()
, will ignore these properties. Those functions only incorporate the properties defined in the primary constructor.
Sometimes, this can be a feature: you might want some properties to be ignored for equals()
and hashCode()
. Sometimes, this can be a bug: you might not realize that copy()
only copies a subset of your properties.
Prev Table of Contents Next
This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.