Skip to Content
Course content

228: Migrating a Java Codebase to Kotlin Incrementally

Click on the "Edit" button in the top corner of the screen to edit your slide content.

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:

  1. Convert the Invoice class into a Kotlin data class. Ensure the id is non-nullable and the total is nullable (to reflect that some invoices might not have a total yet).
  2. Convert the InvoiceProcessor class to Kotlin.
  3. Refactor the printInvoice method to remove any !! operators. Instead, use a safe call ?. or a smart cast to handle the possibility that the invoice object or its total might be null.
  4. Ensure the final printInvoice logic prints "Total: N/A" if the total is null.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.