Skip to Content
Course content

230: Kotlin Style Guide and Ktlint

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

You've probably noticed by now that Kotlin is a flexible language, but flexibility can lead to a "wild west" codebase if you're working in a team. I've spent years cleaning up projects where three different developers had three different ideas about where a curly brace should go. It's a waste of cognitive energy. That's why we use the Kotlin Style Guide and a tool called Ktlint to automate the boring part of code reviews.

Starting with some "cowboy" code

To show you how this works, I'm going to write a small OrderProcessor. I'll intentionally write this with some bad habits—things that technically compile but make a seasoned Kotlin dev cringe. I'm talking about inconsistent indentation, weird spacing, and some Java-isms that don't belong here.

class OrderProcessor {
    fun processOrders(orders: List<Order>) {
        val filteredOrders = orders.filter { it.isValid }
        
        for (order in filteredOrders) {
            println("Processing order: " + order.id)
            // Notice the weird spacing below
            if(order.amount > 100){
                applyDiscount(order)
            }
        }
    }

    private fun applyDiscount(order: Order) 
    { 
        println("Discount applied to ${order.id}")
    }
}

data class Order(val id: String, val amount: Double, val isValid: Boolean)

At first glance, it works. But look at applyDiscount. I put the opening brace on a new line. If you're coming from C# or Java, that feels natural, but in Kotlin, it's a no-go. Then there's that List<Order>—which is actually a Java-style generic declaration rather than the standard Kotlin way. It's subtle, but it adds up.

Bringing in the automated referee

I could manually fix this, but that's a waste of my time. Instead, I'm adding Ktlint to the project. Ktlint is an "anti-bikeshedding" tool. It doesn't give you a thousand configuration options; it mostly just enforces the official Kotlin Style Guide. I usually add it via a Gradle plugin so I can run ./gradlew ktlintCheck as part of my CI pipeline.

When I run the check on the code above, Ktlint screams at me. It flags the missing space before the opening brace in the if statement and, more importantly, that lonely brace on the new line in applyDiscount.

Fighting the formatter and losing (then winning)

Here is where I usually make a mistake: I try to argue with the tool. I remember thinking, "But the new line makes the function start more clearly!" I tried to override the rule in my .editorconfig file to allow it. I spent twenty minutes fighting the configuration only to realize that I was fighting the industry standard.

The real "senior" move is to stop resisting and just run ./gradlew ktlintFormat. Let the machine handle the aesthetics so you can handle the logic. After running the auto-formatter, my code transforms. The braces snap into place, and the spacing becomes consistent.

class OrderProcessor {
    fun processOrders(orders: List<Order>) {
        val filteredOrders = orders.filter { it.isValid }

        for (order in filteredOrders) {
            println("Processing order: ${order.id}")
            if (order.amount > 100) {
                applyDiscount(order)
            }
        }
    }

    private fun applyDiscount(order: Order) {
        println("Discount applied to ${order.id}")
    }
}

data class Order(val id: String, val amount: Double, val isValid: Boolean)

Refining the logic to meet the guide

Ktlint handles the whitespace, but the Style Guide also covers things the formatter can't always automate, like naming conventions and the use of val versus var. I noticed I used string concatenation "Processing order: " + order.id in my first draft. The style guide strongly prefers string templates.

I've updated that to ${order.id}. It's not just about looks; it's about idiomatic Kotlin. When you follow these rules, any other Kotlin developer can jump into your project and feel immediately at home because the code "smells" right.




📋 Practical Task

Clean Up the Messy InventoryManager

Below is a piece of code for an InventoryManager that violates several Kotlin Style Guide rules. Your task is to rewrite this snippet so that it would pass a Ktlint check and follow idiomatic Kotlin standards. Fix the brace placements, the spacing, the string concatenation, and the inconsistent naming.

class InventoryManager {
    var item_count = 0

    fun addItem(itemName: String, quantity: Int) 
    {
        item_count += quantity
        println("Added " + quantity + " of " + itemName)
    }

    fun checkStock(name:String):Boolean {
        if(item_count > 0){
        return true
        } else {
            return false
        }
    }
}
Rating
0 0

There are no comments for now.

to be the first to leave a comment.