If:
- You are a
Javadeveloper tired of its verbose syntax - You are a developer who wants to write less code so you can leave work on time ;))
- You are a team lead writing post-mortems for production bugs caused by code review fatigue
- You believe in the philosophy of
less code, less bugs
Then Kotlin can definitely help you ;))
Drawn together by strengths
Driven apart by misunderstandings
— Trí Xàm ;))
Here are the key strengths of Kotlin compared to Java, which will hopefully inspire you to explore Kotlin:
- JVM language
- Clean, compact, sugar syntax
- Null safety
- Unchecked exceptions
- Data classes
- Default values
- Named arguments
- Functional programming support
- Extension functions
- Coroutines: lightweight threads
1. JVM language
Kotlin, much like Scala, Clojure, Groovy…, is a JVM language (full list). Therefore, it inherits several major advantages:
- Compiles to bytecode and runs on the JRE (Java Runtime Environment): Reuses existing infrastructure without changes.
- Shares Java’s vast ecosystem and libraries: As one of the most popular languages in the world,
Javaprovides an enormous ecosystem. You won’t need to spend time searching for or rewriting libraries when adopting Kotlin. - Interoperates seamlessly with Java code in the same module/project: If you have an existing
Javaproject, you don’t need to rewrite it 100%. With just a few build configurations, you can have a hybrid project containing bothJavaandKotlin. This is ideal for enterprise projects requiring stability and safety. Personally, I took over several Java projects and integratedKotlinover two years ago. While Kotlin lines of code only accounted for around35%, they handled roughly70%of the business logic.
I will write a few articles sharing practical experiences and conversion strategies from Java to Kotlin. Stay tuned!!
Update: Check out the series here: From Java to Kotlin
2. Clean, compact, sugar syntax
Discussing how Kotlin simplifies code could take several articles, but here are the highlights I love most. Assuming you are already familiar with Java, I’ll jump straight into Kotlin syntax:
Main function
| |
Functions
| |
Or more concisely with single-expression syntax:
| |
Variables
Kotlin provides two keywords, val and var, for variable declarations. Types are inferred automatically if omitted.
val is immutable (read-only), while var is mutable:
| |
String templates
| |
Statements as expressions
Statements like if/else, try/catch, and when can return expressions:
| |
Type checks and automatic casts
| |
Elimination of new keyword
| |
3. Null safety
As you may know, Null is considered the billion-dollar mistake, and Kotlin provides powerful tools to eliminate NullPointerException at compile time.
By default, types in Kotlin are non-nullable:
| |
To allow a variable to hold null, explicitly append ?:
| |
Direct method calls on nullable types are disallowed by the compiler:
| |
To call methods safely, use the safe-call operator ?.:
| |
Use the Elvis operator ?: to provide a fallback default:
| |
Safe Casts
| |
4. Unchecked exceptions
In Try/Catch Explain, I discussed why checked exceptions often create unnecessary friction.
Many others in the industry share this viewpoint:
- Checked Exceptions are Evil
- It’s almost 2020 and yet… Checked Exceptions are still a thing
- Java’s Checked Exceptions Are Evil? (2015)
Fortunately, all exceptions in Kotlin are unchecked ;))
5. Data classes
Suppose we need a User class with two fields, name and age. In Kotlin, all you need is:
| |
Kotlin automatically generates:
- Getters and setters (for
varproperties) equals()andhashCode()toString()likeUser(name=John, age=42)copy(): to clone instances while altering specific fields (covered in 7. Named arguments)
6. Default values
Kotlin supports default parameter values in constructors and methods:
| |
Now you can instantiate objects flexibly:
| |
7. Named arguments
Combining default values with named arguments gives you clean, expressive code without needing builder patterns:
| |
8. Functional programming support
Lambdas were a huge improvement in Java 8, and Kotlin elevates functional programming even further.
Suppose we define a Student class:
| |
Given a list of students, suppose the requirement is:
Get 10 passing students with an average grade greater than 4.0
Prioritize students with higher grades
Sorted alphabetically by student name (surname first, then name)
In Java, this requires considerable ceremony. In Kotlin, it takes just 4 fluent lines ;)):
| |
This example comes from this blog post. I will write a dedicated deep dive when time permits ;))
9. Extension functions
This is one of my favorite features in Kotlin. You can extend existing classes with new methods or properties without modifying their original source code—making it fantastic for integrating third-party libraries and modules. Remember that this is compiler syntactic sugar and does not modify the underlying class hierarchy.
For instance, adding a checkEmpty helper to String?:
| |
Similarly, we can define extension properties:
| |
10. Coroutines: lightweight threads
When working on network programming in the past, I dealt extensively with Java threads and encountered several drawbacks:
- Heavy resource usage: Each thread allocates roughly 330KB (32-bit OS) to 1MB (64-bit OS) of stack space, limiting the number of concurrent threads a single process can spawn.
- Resource contention and locking: Increases project complexity and performance overhead.
- Challenging debugging, tracing, and testability.
- Risk of deadlocks.
These challenges are addressed by Coroutines. A full series from basics to advanced patterns is necessary to cover coroutines comprehensively.
As a quick demonstration of what coroutines make possible that traditional Java threads struggle with ;)):
| |
The code above spawns 100,000 coroutines, each printing a dot after a 5-second delay. Trying this with 100k OS threads in Java would quickly trigger an OutOfMemoryError.
Update: Check out the full series on Kotlin Coroutines
Conclusion
I hope this overview inspires you to dive into Kotlin and consider adopting it for your upcoming projects!