Secondary constructor with atStartOfDay

Gigasecond
Gigasecond in Kotlin
import java.time.LocalDate
import java.time.LocalDateTime

class Gigasecond(baseDatetime: LocalDateTime) {
    private val gigaseconds: Long = 1_000_000_000
    val date: LocalDateTime = baseDatetime.plusSeconds(gigaseconds)

    constructor(baseDate: LocalDate) : this(baseDate.atStartOfDay())
}

This approach starts by importng from libraries for what is needed.

The Gigasecond class is defined with a primary constructor that takes a LocalDateTime.

A private val is defined to hold the value for one billion seconds. A val with a meaningful name is used instead of using the 1000000000 value as a magic number. Note that digit separators (_) can make long numbers more readable.

Another val is defined that uses the plusSeconds method to add a billion seconds to the value passed into the primary constructor.

The constructor keyword is used to define a secondary constructor that takes a LocalDate. It uses the this keyword to call another constructor (in this case, the primary constructor.) The atStartOfDay method is used to convert the LocalDate to the LocalDateTime type accepted by the primary constructor. Calling one constructor from another is referrred to as "constructor chaining".

4th Sep 2024 · Found it useful?