Search code examples
kotlindata-class

Kotlin data class with additional properties not in constructor


Starting out with Kotlin and wanting to make a data class

data class Person(val Email: String, val firstName: String, val lastName: String)

But let's say I want to add additional properties that I don't know at the time when I am using the constructor but I want to store this data at a later point when I am aware of it for example a person's mood (Represented as a String)

In Java I would make a data class like this. I would be able to not include it in the Constructor and make a getter where I could set it at a later time.

public class Person{

     private String email;
     private String firstName;
     private String lastName;
     private String mood;

     public person (String email, String firstName, String lastName){
      this.email = email;
      this.firstName = firstName;
      this.lastName = lastName;
    } 

    public setMood(String mood){
     this.mood = mood;
    }
}

Kotlin doesn't appear to have an answer on this or if it does I do not know how to phrase correctly. Hence why this question could already be answered and I am unable to find it.

I do understand that by not including mood in the data class line Kotlin may not be able to identify mood as part of the data class but aside from including it in the constructor and setting it to null I'm not sure what else to do or is that what I am supposed to do?


Solution

  • You should be able to just add it as a property to Person. In Kotlin, a data class is still a class, it just comes with some extras (toString, copy constructors, hashCode/equals, etc). You can still define any properties that you want.

    data class Person(val Email: String, val firstName: String, val lastName: String) {
        var mood: String? = null
    }
    

    In this case it is nullable, because as you stated, you might not know the mood until later.