Search code examples
kotlindata-class

Kotlin data class with default constructor parameter


I want to use a data class with a property that has a default value in the constructor based on another constructor parameter. It works exactly as I want it if I use a normal (non-data) class:

import java.time.Clock
import java.time.Instant

class MyObject(
    clock: Clock = Clock.systemUTC(),
    val name: String,
    val timeCreated: Instant = clock.instant()
)

fun main() {
    val a = MyObject(name = "Fred")
    println(a.timeCreated)
}

But if I try to make it a data class, it doesn't compile:

Primary constructor of data class must only have property ('val' / 'var') parameters.

I don't want the clock parameter to be a property, as it's only used for testing. But I do want the class to be a data class with its autogenerated toString, copy and other bells and whistles. What can I do?


Solution

  • Just add a secondary constructor:

    data class MyObject(
        val name: String,
        val timeCreated: Instant
    ) {
        constructor(
            name: String,
            clock: Clock = Clock.systemUTC(),
            timeCreated: Instant = clock.instant(),
        ): this(name, timeCreated)
    }
    

    Note that the clock parameter should be after name, otherwise you need to specify the parameter names when calling the constructor.