k314159
k314159

Reputation: 11246

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?

Upvotes: 2

Views: 30

Answers (1)

Sweeper
Sweeper

Reputation: 273540

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.

Upvotes: 2

Related Questions