Continuing with the domain of insurance, suppose we want to find the duration between the start and end dates of policies. We may write something like this:
| DateUtil.durationBetween(begin, end) |
But that’s so boring, verbose, and nonintuitive. It would be way better to write more simply:
| begin - end |
If begin and end are instances of LocalDate, the previous snippet won’t run without extra effort, since - isn’t valid by default on LocalDate. Thankfully, the extra effort is minor.
We can create a minus() extension function and mark it as an operator. This allows us to use - on the two instances of LocalDate.
| operator fun LocalDate.minus(other: LocalDate) { |
| Period.between(this, other).apply { |
| println("$years years $months months $days days") |
| } |
| } |
Using the Kotlin naming convention, we can now call the extension function minus(), which automatically maps to the - operator because it’s marked with the operator keyword. Since it’s a binary operator, we pass one parameter as the second operand; the receiver object of this extension function, this, serves as the first operand for the operator.
Here’s the output from executing the Kotlin script:
| 0 years 1 months 15 days |
Adding a - operator to LocalDate was quite simple since we’re able to use instances of date like they are numerical values. Sometimes, however, we have to put in more effort to make numerical computations fluent, as we’ll see next.
44.200.175.46