Multiline arithmetic operation assignment

I tried the following:

            val remainingSeconds = endDate.toEpochSecond(ZoneOffset.UTC)
                - dateTime.toEpochSecond(ZoneOffset.UTC)
                + randomInt(3600, 72000) // 1 to 20 hours

and ended up with remainingSeconds having the wrong value (only the first line)

I think I get the why, there’s no delimiters so line break equals java’s ; the other lines are considered to be just plain statements

            val remainingSeconds = endDate.toEpochSecond(ZoneOffset.UTC);
                - dateTime.toEpochSecond(ZoneOffset.UTC);
                + randomInt(3600, 72000); // 1 to 20 hours

So, search fails me, what options do I have to write this correctly?, well, besides putting it all in one line, and using parentheses

Just put operators at the end of a line, not the beginning. It won’t look exactly as you like though.

1 Like

Another way you can do it is by using parentheses:

        val remainingSeconds = (endDate.toEpochSecond(ZoneOffset.UTC)
            - dateTime.toEpochSecond(ZoneOffset.UTC)
            + randomInt(3600, 72000) // 1 to 20 hours
        )

(Some linters may be very picky about the indentation when you do this.)

2 Likes

I’m not sure which API you are sticking to, but here it is how you can write this:

// java.time
val remainingSeconds = Duration.between(dateTime, endDate)
	.plusSeconds((3_600L..72_000L).random())
	.seconds

// kotlinx.datetime
val remainingTime = endDate.toInstant(TimeZone.UTC) -
	dateTime.toInstant(TimeZone.UTC) +
	(3_600L..72_000L).random().seconds
val remainingSeconds = remainingTime.inWholeSeconds

Seems a little clucky to me when you try to use normal operators across multiple lines.

FWIW I tried doing OP’s code in IntelliJ, and it gave me a warning that the second line is an “Unused Unary operator”. I actually didn’t think it would compile; I didn’t know Kotlin had unary operators. So I learned something new today!

Most languages have a unary minus, at least — else you couldn’t refer to e.g. -x. The boolean negation (‘not’) operator (! in Kotlin) is also unary, as are the pre-/post-increment and -decrement operators ++ and --, and the unary +.

(However, the unary + and - are the only ones which are also binary operators, so the only ones you need to take care of when line-wrapping.)

2 Likes