Skip to Content
Course content

74: Practice Exercise: Refactoring Java Code Idiomatically into Kotlin

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

I've seen this happen in almost every professional transition from Java to Kotlin: a developer discovers the "Convert Java File to Kotlin File" shortcut in IntelliJ, hits the button, and assumes the job is done. They see the code is now in a .kt file, it compiles, and the tests pass, so they check it into the repo.

The Converter Button is the Finish Line

The misconception here is that the automated converter produces idiomatic Kotlin. It doesn't. It produces Java written with Kotlin syntax. The converter is designed to ensure the code is functionally identical and safe, which means it often preserves Java's verbosity, manual null checks, and imperative loop structures because that's the safest way to migrate without breaking logic.

// A typical Java method
public List<User> getActiveAdmins(List<User> users) {
    List<User> admins = new ArrayList<>();
    if (users != null) {
        for (User user : users) {
            if (user != null && user.isAdmin() && user.isActive()) {
                admins.add(user);
            }
        }
    }
    return admins;
}

If you run this through the converter, you'll get something like this:

fun getActiveAdmins(users: List<User>?): List<User> {
    val admins = ArrayList<User>()
    if (users != null) {
        for (user in users) {
            if (user != null && user.isAdmin && user.isActive) {
                admins.add(user)
            }
        }
    }
    return admins
}

It's valid Kotlin, sure. But it's boring. It's clunky. It ignores everything that makes Kotlin powerful. I call this "Java-ish" code, and it's a smell that tells me the developer hasn't actually embraced the language yet.

Hunting for Expressions and Functional Pipelines

To move from "Java-ish" to "Idiomatic," you have to stop thinking in terms of instructions (do this, then do that) and start thinking in terms of transformations. In the example above, we aren't actually "managing a list"—we are filtering a stream of data.

When I refactor this, I look for three things: the ability to turn the function into a single expression, the removal of explicit null-check blocks, and the replacement of for loops with collection functions. Here is how that same method looks when written by someone who actually wants to use Kotlin:

fun getActiveAdmins(users: List<User>?): List<User> =
    users?.filterNotNull()
          ?.filter { it.isAdmin && it.isActive } 
          ?: emptyList()

Notice the difference? We've collapsed ten lines of boilerplate into a single expression. We used the safe call operator (?.) and the Elvis operator (?:) to handle the nullability of the list, and we used filter to handle the logic. It's more declarative; it tells the reader what is happening rather than how the computer should move pointers around in memory.

As you go through this practice exercise, don't just look for syntax errors. Look for "Java-isms." If you see a for loop, ask yourself if map, filter, or any could replace it. If you see an if (x != null) block, try to use ?.let { ... } or a safe call. That's where the real learning happens.




📋 Practical Task

Refactoring the Legacy OrderProcessor

You have been handed a legacy Java class used for processing customer orders. It works, but it is verbose and follows old Java patterns. Your task is to rewrite the processOrders method in the OrderProcessor class to be idiomatic Kotlin.

The Legacy Java Code:

public class OrderProcessor {
    public List<Order> getHighValuePaidOrders(List<Order> orders, double minAmount) {
        List<Order> result = new ArrayList<>();
        if (orders != null) {
            for (Order order : orders) {
                if (order != null) {
                    if (order.isPaid() && order.getAmount() >= minAmount) {
                        result.add(order);
                    }
                }
            }
        }
        return result;
    }
}

Requirements for your refactor:

  • Convert the method into a single-expression function (remove the { return ... } block).
  • Eliminate the explicit if (orders != null) check using a safe call and the Elvis operator.
  • Replace the for loop and inner if checks with a functional collection pipeline (e.g., filter).
  • Ensure the method returns an empty list if the input orders list is null.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.