From Java to Kotlin – Part III: Default Values and Named Arguments
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 3: Constructors are supposed to be simple.
Java sometimes seems to disagree.
The problem
We want to create an object where:
-
some values are optional
-
defaults make sense
-
readability matters
Bonus points if we don’t need five constructors.
The Java way
In Java, optional values usually mean:
-
multiple constructors
-
builder patterns
-
or both
public record JavaPerson(String name, Integer age) {
public JavaPersoon() {
this("John Doe", 100);
}
}
Usage:
new JavaPerson("Jan", 42);
new JavaPerson();
This works. But once the number of fields grows, so does the complexity.
The Kotlin way
Kotlin supports default parameter values and named arguments.
data class KotlinPerson(val name: String = "John Doe", val age: Int = 100) { }
Usage:
val p1 = KotlinPerson(name = "Jan", age = 42)
val p2 = KotlinPerson()
No overloads.
No builders.
No guessing what 42 means.
Named arguments also improve readability immediately:
KotlinPerson(age = 42, name = "Jan")
Order no longer matters. Intent does.
Why this matters
Named arguments:
-
eliminate “magic numbers”
-
improve readability
-
reduce constructor overloads
Defaults reduce noise. Your code says what it means.
Takeaway
Java offers patterns. Kotlin offers language features.
Both work. One requires less discipline.