0

I'm new in Kotlin and I need to create 2 date ranges. One that shows the dates as they are created in the constructor and another that modifies the end date with a default date in case it is null or greater than the default date. For this I had thought to create an abstract class with a start and end date and then create 2 data classes to implement this abstract class and put this business rule in one of them. This is the code I have so far:

abstract class BaseLocalDateRange (
    open val startDate: LocalDate?,
    open val endDate: LocalDate?
    )

data class LocalDateRange(
    override val startDate: LocalDate?,
    override val endDate: LocalDate?
): BaseLocalDateRange(
    startDate,
    endDate
)

data class LocalDateRangeEndDate(
    override val startDate: LocalDate?,
    override val endDate: LocalDate?
): BaseLocalDateRange(
    startDate,
    if (endDate== null || endDate > LocalDate.of(2099, 12, 31)) LocalDate.of(2099, 12, 31) else endDate
)

My questions are:

  • Is this ok or there is a better way to approach this problem?
  • I would like to have the "default date" in properties and use it here, but I don't really know how, so if someone has an idea of how to handle this it would be great.

Thank you!

2
  • Please define what a "better" way means. Commented Aug 10, 2021 at 9:43
  • "I would like to have the 'default date' in properties" What properties? You mean a file stored somewhere? Or a named constant? Commented Aug 10, 2021 at 9:45

1 Answer 1

1

no you don't neet to override startDate and endDate

and you can DEFAULT_END_DATE at companion

package org.example

import java.time.LocalDate

abstract class BaseLocalDateRange(
    protected val startDate: LocalDate?,
    protected val endDate: LocalDate?
){
    companion object{
        val DEFAULT_END_DATE: LocalDate = LocalDate.of(2099, 12, 31)
    }
}


class LocalDateRange(startDate: LocalDate?, endDate: LocalDate?) : BaseLocalDateRange(startDate, endDate)

class LocalDateRangeEndDate(startDate: LocalDate?, endDate: LocalDate?) : BaseLocalDateRange(
    startDate,
    if (endDate!=null && endDate > DEFAULT_END_DATE) DEFAULT_END_DATE else endDate
)


Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.