Kotlin is allowing me to use the latest Java Libraries without updating the JDK. Here is how.

Raphael De Lio
3 min readJun 8, 2020

--

Twitter | LinkedIn | YouTube | Instagram

Whether you’re using JDK 8 or another one, you probably have come across a function that would really come in handy just to find out it was only implemented in a newer JDK version. Really frustrating, right? You would have to implement a util class, then instantiate that util class

Well, you got the idea… Your code could look more elegant and readable, but instead you will need to implement Util classes to give classes that cannot be edited new functionality.

Kotlin tackles that problem with Extension Functions and gives us a workaround.

Let’s say, for example, you’re developing in Java 8 and you want to calculate the period between two LocalDateTime instances.

1.   // Java
2. LocalDateTime firstDateTime = LocalDateTime.of(2020,
Month.JUNE, 3. 29, 17, 30, 40);
4.
5. LocalDateTime secondDateTime = LocalDateTime.of(2020,
Month.JUNE, 29, 19, 30, 40);
6.
7. // Kotlin
8. val firstDateTime = LocalDateTime.of(2020, Month.JUNE, 29, 19,
30, 40)
9.
10. val secondDateTime = LocalDateTime.of(2020, Month.JUNE, 29,
19, 30, 40)

To do it, you could use java.time.Duration:

1.   // Java
2. Duration duration = Duration.between(firstDateTime,
secondDateTime);
3.
4. // Kotlin
5. val duration = Duration.between(firstDateTime, secondDateTime)

And now you want to output this information in an specific format, such as HH:mm:ss.

Duration holds the time in seconds and has function such as getHours() and getMinutes() that converts the duration from seconds to those time units.

But yet, you would need to calculate the remaining minutes when dividing by minutes in an hour and the remaing seconds when dividing by seconds in a minute.

There are no native functions in Java 8 to calculate these operations, they were only introduced in Java 9 as toMinutesPart() and toSecondsPart()

So, in Java 8, you would probably create a class like DurationUtils and implement these methods yourself:

public final class DurationUtils {
static final int MINUTES_PER_HOUR = 60;
static final int SECONDS_PER_MINUTE = 60;
public int toMinutesPart(Duration d){
return (int) (toMinutes() % MINUTES_PER_HOUR);
}
public int toSecondsPart(Duration d){
return (int) (seconds % SECONDS_PER_MINUTE);
}
public static String format(Duration d) {
long seconds = duration.getSeconds();
return String.format(
"%d:%02d:%02d",
toHours(d),
toMinutesPart(d),
toSecondsPart(d));
}
}

And then, to implement it, you would need to call the function from DurationUtils and send your Duration instance as a parameter. As you can see:

public static void main(String []args){
LocalDateTime firstDateTime = LocalDateTime.of(2020, Month.JUNE,
3. 29, 17, 30, 40);

LocalDateTime secondDateTime = LocalDateTime.of(2020, Month.JUNE,
29, 19, 30, 40);
Duration duration = Duration.between(firstDateTime,
secondDateTime);
String formattedDuration = DurationUtils.format(d);
}

In Kotlin, on the other hand, there is a more elegant and readable way of implementing the same thing, and that’s by implementing Extension Functions .

We don’t even need a class to do it, just a Kotlin file, as you can see:

const val MINUTES_PER_HOUR = 60
const val SECONDS_PER_HOUR = 60
fun Duration.toMinutesPart() = toMinutes() % MINUTES_PER_HOURfun Duration.toSecondsPart() = seconds % SECONDS_PER_HOURfun Duration.format(): String {
val hours = "${toHours()}".padStart(2, '0')
val minutes = "${toMinutesPart()}".padStart(2, '0')
val seconds = "${toSecondsPart()}".padStart(2, '0')

return "$hours:$minutes:$seconds"
}

Pay attention that toMinutesPart() and toSecondsPart() are being called as if they were part of the Duration class. We don’t need to pass the Duration object to the function or use any other third class.

fun main(args: Array<String>) {
val firstDateTime = LocalDateTime.of(2020, Month.JUNE, 29, 19,
30, 40)

val secondDateTime = LocalDateTime.of(2020, Month.JUNE, 29, 19,
30, 40)
val duration = Duration.between(firstDateTime, secondDateTime) val String = duration.format()
}

In the background, Kotlin will compile these functions as static functions and implement them in the same way we do in Java.

There is no doubt, though, that our code looks cleaner and is more readable when using extension functions.

Contribute

Writing takes time and effort. I love writing and sharing knowledge, but I also have bills to pay. If you like my work, please, consider donating through Buy Me a Coffee: https://www.buymeacoffee.com/RaphaelDeLio

Or by sending me BitCoin: 1HjG7pmghg3Z8RATH4aiUWr156BGafJ6Zw

Follow Me on Social Media

Stay connected and dive deeper into the world of Kotlin with me! Follow my journey across all major social platforms for exclusive content, tips, and discussions.

Twitter | LinkedIn | YouTube | Instagram

--

--

Raphael De Lio
Raphael De Lio

Written by Raphael De Lio

Software Engineer | Developer Advocate | International Conference Speaker | Tech Content Creator | Working @ Redis | https://linktr.ee/raphaeldelio

No responses yet