How to convert following java code to Kotlin

I have java code like this:

    public class IntervalHolder
    {
        public final Interval last24Hrs;
       
        public IntervalHolder()
        {
            DateTime now = DateTime.now().minuteOfHour().roundFloorCopy();
            DateTime oneDayAgo = now.minusHours(24);

            last24Hrs = new Interval(oneDayAgo, now);
        }
    }

How do I express this in Kotlin?

The best I could come up with is this:

class IntervalHolder
{

    lateinit var last24Hrs: Interval;

    constructor()
    {
        val now = DateTime.now().minuteOfHour().roundFloorCopy()
        val oneDayAgo = now.minusHours(24)

        last24Hrs =  Interval(oneDayAgo, now)
    }
}

but now last24Hrs is a mutable property instead of being immutable like in the java code.

What you are looking for here is an init block as in this code (which happens to be what the Kotlin plugin’s feature to convert Java code to Kotlin generates for you):

class IntervalHolder
{
    val last24Hrs: Interval

    init
    {
        val now = DateTime.now().minuteOfHour().roundFloorCopy()
        val oneDayAgo = now.minusHours(24)

        last24Hrs = Interval(oneDayAgo, now)
    }
}
1 Like

And on a side note, since I assume you are using JodaTime, based on DateTime class, I would use

    val oneDayAgo = now.minusDays(1)

or

    val oneDayAgo = now.minus(Days.days(1))

where Days.days(1) would be more likely moved to a constant.

If somewhere you defined this:

val Int.days : Days
    get() = Days.days(this)

You could even do:

val oneDayAgo = now.minus(1.days)
1 Like