-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Null Safety
-
Section 4: Object-Oriented Kotlin
-
Section 5: Functional Kotlin
-
Section 6: Coroutines
-
Section 7: Collections Deep Dive
-
Section 8: Type System Deep Dive
-
Section 9: Interop and Tooling
-
Section 10: Kotlin DSLs and Patterns
-
Section 11: Testing and Quality
-
Section 12: Server-Side Kotlin
-
Section 13: Practical Projects
-
Section 14: Interview Practice
-
Section 15: More Practice Exercises
-
Section 16: More Standard Library
-
Section 17: Multiplatform Kotlin
-
Section 18: kotlin.collections In Depth
-
Section 19: kotlin.text In Depth
-
Section 20: kotlin.ranges and kotlin.sequences
-
Section 21: kotlin.io and File Handling
-
Section 22: kotlinx.coroutines Deep Dive
-
Section 23: kotlin.reflect
-
Section 24: Android Development with Kotlin Overview
-
Section 25: Kotlin Multiplatform Deep Dive
-
Section 26: Kotlin for Backend Deep Dive
-
Section 27: Kotlin Design Patterns
-
Section 28: Advanced Language Features
-
Section 29: More Practice Exercises
-
Section 30: More Interview Practice
-
Section 31: Kotlin Type System Deep Dive
-
Section 32: Kotlin Null Safety Advanced
-
Section 33: Kotlin Testing Deep Dive
-
Section 34: Kotlin Build Tooling Deep Dive
-
Section 35: Kotlin Serialization
-
Section 36: Kotlin Performance Considerations
-
Section 37: Kotlin Native Overview
-
Section 38: Kotlin for Data and Scripting
-
Section 39: More Coroutines Practice
-
Section 40: More Android-Adjacent Patterns
-
Section 41: More Practical Projects
-
Section 42: More Design and Architecture Practice
-
Section 43: Kotlin Language Evolution
-
Section 44: More Interview and Review
-
Section 45: Kotlin Delegation Patterns Deep Dive
-
Section 46: Kotlin Annotations Deep Dive
-
Section 47: Kotlin for Gradle Plugin Development
-
Section 48: Kotlin Concurrency Beyond Coroutines
-
Section 49: Kotlin Compiler Internals
-
Section 50: Real-World Kotlin Case Studies
-
Section 51: Final Practice Projects
-
Section 52: Kotlin for Server-Side Reactive Programming
-
Section 53: More Practice and Drills
-
Section 54: Kotlin Security Practices
228: Migrating a Java Codebase to Kotlin Incrementally
If you're staring at a massive Java legacy project, the thought of rewriting it all in Kotlin is probably terrifying. I've been there. The "big bang" rewrite is almost always a mistake—it creates a feature freeze that stakeholders hate and introduces a mountain of regressions. The secret is incremental migration. Kotlin was designed specifically for this; it's binary-compatible with Java, meaning you can have a project that is 99% Java and 1% Kotlin, and it'll run just fine.
Let's walk through this using a small "Order Management" example. Imagine we have a Java-based system that handles customer orders. We want to move to Kotlin, but we can't stop the world to do it.
Starting with the low-hanging fruit
When I start a migration, I always look for the "dumb" data holders first. POJOs are the perfect starting point because they're low risk and provide immediate value through Kotlin's data class. Here is our starting Java Order class:
public class Order {
private final String orderId;
private final double amount;
public Order(String orderId, double amount) {
this.orderId = orderId;
this.amount = amount;
}
public String getOrderId() { return orderId; }
public double getAmount() { return amount; }
}
I'll convert this to Kotlin first. I'm not using the auto-converter yet because I want to be intentional about the types. In Kotlin, this becomes a one-liner:
data class Order(val orderId: String, val amount: Double)
Now, any existing Java code that called getOrderId() still works perfectly because Kotlin generates those getters under the hood. We've reduced 15 lines of boilerplate to one, and we haven't broken a single thing.
Adding new logic in Kotlin
Now that our data model is shifting, it's a great time to write new features in Kotlin. Let's say we need a DiscountCalculator. Instead of adding another Java class to the pile, I'll write it in Kotlin and have it interact with our (now Kotlin) Order class.
class DiscountCalculator {
fun calculateDiscount(order: Order): Double {
return if (order.amount > 100.0) {
order.amount * 0.1
} else {
0.0
}
}
}
At this point, my project is a hybrid. I have Java services calling Kotlin calculators, which in turn process Kotlin data classes. It feels a bit messy, but it's stable.
The "Auto-Convert" trap
Eventually, you'll get impatient and use the "Convert Java File to Kotlin File" tool in IntelliJ. I did this with my OrderService.java and immediately hit a snag. Here was the Java method:
public void processOrder(Order order) {
if (order != null) {
System.out.println("Processing: " + order.getOrderId());
}
}
The converter turned it into this:
fun processOrder(order: Order?) {
if (order != null) {
println("Processing: ${order!!.orderId}")
}
}
Wait—why is there a !! (the non-null assertion operator) inside a null check? I initially left it there because the code compiled and worked. But then I realized I was introducing a potential NullPointerException risk if the logic changed later. The converter used !! because it wasn't 100% sure about the nullability of the Java-originated Order type.
I corrected this by leveraging Kotlin's smart casting. If I check if (order != null), Kotlin knows order is non-null inside that block. I stripped out the !! and let the compiler handle it naturally:
fun processOrder(order: Order?) {
if (order != null) {
println("Processing: ${order.orderId}") // Smart cast! No !! needed.
}
}
Wiring it all together
Finally, we have our Java-based Main class. Notice how it doesn't care that the classes it's using are now Kotlin. It just sees classes and methods.
public class Main {
public static void main(String[] args) {
Order myOrder = new Order("ORD-123", 150.0);
DiscountCalculator calc = new DiscountCalculator();
double discount = calc.calculateDiscount(myOrder);
System.out.println("Discount: " + discount);
}
}
You can keep this pattern going: convert a POJO, write a new utility in Kotlin, convert a service, and repeat. You aren't fighting the codebase; you're evolving it.
📋 Practical Task
Exercise: Refactoring the Legacy Invoice Manager
You have been handed a legacy Java class Invoice and a Java service InvoiceProcessor. Your goal is to migrate these incrementally to Kotlin while fixing a null-safety issue.
The Java Code:
// Invoice.java
public class Invoice {
private String id;
private Double total;
public Invoice(String id, Double total) {
this.id = id;
this.total = total;
}
public String getId() { return id; }
public Double getTotal() { return total; }
}
// InvoiceProcessor.java
public class InvoiceProcessor {
public void printInvoice(Invoice invoice) {
if (invoice != null) {
System.out.println("Invoice " + invoice.getId() + " total is " + invoice.getTotal());
}
}
}
Your Task:
- Convert the
Invoiceclass into a Kotlindata class. Ensure theidis non-nullable and thetotalis nullable (to reflect that some invoices might not have a total yet). - Convert the
InvoiceProcessorclass to Kotlin. - Refactor the
printInvoicemethod to remove any!!operators. Instead, use a safe call?.or a smart cast to handle the possibility that theinvoiceobject or itstotalmight be null. - Ensure the final
printInvoicelogic prints "Total: N/A" if the total is null.
There are no comments for now.