From Java to Kotlin – Part I: String extensions without the boilerplate
Considering a move to Kotlin? Coming from a Java background? In this short series of blog posts, I’ll take a look at familiar, straightforward Java concepts and demonstrate how you can approach them in Kotlin. While many of these points have already been discussed in earlier posts by colleagues, my focus is simple: how you used to do it in Java, and how you do it in Kotlin.
Case 1:
You are working on an application in Java and you need a reusable way to modify a String.
Nothing fancy. No frameworks. Just a small helper.
Something like: message.reverse();
Can Java do this? Sort of. Does it feel great? Not really.
Let’s take a look.
The problem
We want to reverse a String and reuse that logic in multiple places.
Ideally, it should be readable and easy to discover.
Sounds harmless, doesn’t it? Famous last words.
The Java way
In Java, you can’t add methods to String.
So we reach for the classic solution: a utility method.
private static String reverse(String input) {
return new StringBuilder(input).reverse().toString();
}
Usage: System.out.println(reverse(message));
This works. It’s fast. It’s correct.
But:
-
The method lives outside
String -
You have to remember where it is *(1)
-
Chaining gets ugly fast
-
Autocomplete won’t help much
Java isn’t wrong here — it’s just very… honest.
The Kotlin way
Kotlin allows you to define extension functions. They let you add behavior to existing classes without modifying them.
fun String.reverse(): String = this.reversed()
Usage:
println(message.reverse())
That’s it. * No utility class. * No static imports. * No ceremony.
Almost suspiciously nice.
Is String really modified?
No.
Extension functions:
-
Do not change the original class
-
Are resolved at compile time
-
Compile down to static methods
You get better readability without breaking encapsulation. Everybody wins.
Why this matters
Once extensions exist, code starts to read like intent instead of plumbing.
println(message.reverse().reverse() == message)
In Java, that line would already be negotiating for more parentheses.
Takeaway
Java makes you work around the language. Kotlin lets you work with it.
Extension functions are one of those features that feel unnecessary — until you use them.
After that, going back feels a bit like typing with mittens on.
(1) To be fair, Kotlin doesn’t magically solve this — you still have to decide where your code belongs.