Muhammad Lukman Low
Muhammad Lukman Low

Reputation: 8533

How are secondary kotlin constructor variables passed in?

I am looking at the solution for the gigasecond exercism exercise for Kotlin: http://exercism.io/exercises/kotlin/gigasecond/readme. I can understand how it needs two two constructor because LocalDate and LocalDateTime arguments are passed in when creating the class. What I don't understand is how the below secondary class constructor variables are passed in and used in the class. It seems like the calculation only happens when LocalDateTime arguments are passed in, as calculation is only done with dobWithTime. What magic is happening here ?

data class Gigasecond(val dobWithTime: LocalDateTime) {
    constructor(dateOfBirth: LocalDate) : this(dateOfBirth.atStartOfDay())

    val date: LocalDateTime = dobWithTime.plusSeconds(1000000000)
}

Upvotes: 2

Views: 122

Answers (1)

zsmb13
zsmb13

Reputation: 89548

The secondary constructor just forwards the call to primary constructor with the : this() syntax, while creating the required LocalDateTime object from the LocalDate that it received as its parameter.

You could think of the secondary constructor as a function that does the following:

fun createGigaSecond(dateOfBirth: LocalDate): Gigasecond {
    return Gigasecond(dateOfBirth.atStartOfDay())
}

Except it gets to use the usual constructor syntax instead, and so it can be called as Gigasecond(dataOfBirth) instead of createGigaSecond(dateOfBirth).


From the official documentation about secondary constructors:

If the class has a primary constructor, each secondary constructor needs to delegate to the primary constructor, either directly or indirectly through another secondary constructor(s). Delegation to another constructor of the same class is done using the this keyword.

This is what's happening here.

Upvotes: 5

Related Questions