Why Java Falls Short: 4 Kotlin Features Every Developer Misses
The article compares Java and Kotlin, highlighting four Kotlin features—immutable references, null safety, extension functions, and reified generics—that improve code readability, expressiveness, and maintainability, and shows how Kotlin’s syntax and type system address Java’s shortcomings with practical code examples.
Immutable References
Java allows immutable references but they are not mandatory; by default references are mutable and most Java code does not use them.
Kotlin forces each property and local variable to be declared with val (immutable) or var (mutable) and does not allow reassigning method parameters.
Null Safety
In Java you cannot know whether a variable may be null; Java 8 introduced Optional to represent nullable values. Returning Optional indicates the value may be null, otherwise it is non‑null. Kotlin makes nullability explicit in the type system, requiring every type to be either nullable or non‑nullable.
Example:
val nonNullable: String = computeNonNullableString()
val nullable: String? = computeNullableString()Extension Functions
Kotlin lets you add new functions to existing classes or interfaces without inheritance or the Decorator pattern, using the extensions declaration. This allows adding functionality to third‑party libraries as if the functions were native methods.
Java example:
class StringUtils {
private StringUtils() {}
static String capitalize(String string) {
return string.substring(0, 1).toUpperCase() + string.substring(1);
}
}
String string = randomString();
String capitalizedString = StringUtils.capitalize(string);Kotlin rewrite using an extension function:
fun String.capitalize2(): String {
return substring(0, 1).uppercase() + substring(1)
}
val string = randomString()
val capitalizedString = string.capitalize2()Reified Generics
Kotlin can reify generic type parameters, allowing the type to be known at runtime. In Java, developers often pass a Class<T> argument to retrieve the type, but Kotlin can omit this.
Java Spring BeanFactory example:
public interface BeanFactory {
<T> T getBean(Class<T> requiredType);
}Kotlin reified version:
interface BeanFactory {
fun <T> getBean(): T
}Usage:
val factory = getBeanFactory()
val anyBean = getBean<Any>()According to Nicolas Fränkel, Kotlin has become his preferred JVM language, and he uses Java only when necessary.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Programmer DD
A tinkering programmer and author of "Spring Cloud Microservices in Action"
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
