Estimate project
← All posts

Kotlin: The Gaps and How to Get Around Them

Discover the 5 most notable features Kotlin lacks and the practical ways to work around them.

10 min read
KotlinProgramming LanguagesKotlinServerSide

Kotlin is a modern, thoughtfully designed, general-purpose programming language that is becoming an attractive option for web development. It provides great support for functional programming, full-fledged coroutines, building domain-specific languages, smart type casting, and plenty of other benefits rarely found in other mainstream programming languages. Sadly, nothing is flawless, and Kotlin too has a few shortcomings that more advanced developers may find somewhat inconvenient.

This post isn’t meant to criticize the language. Instead, it aims to get people talking about these missing features, offer practical workarounds, and contribute to improving the language. It also works as a brief guide for developers arriving from other languages, pointing out features they may miss and what they can use in their place.

No package-private access modifier

A typical way of structuring Java code is to split it into packages, each focused on part of a domain. The default access modifier is package-private, so if you leave out an access modifier, the class/member can only be accessed from within the same package. The package can be reached only through specific classes/members that the developer has deliberately made public, and these serve as the package’s facade. This approach fits one of the fundamental ideas of object-oriented programming-encapsulation. Unfortunately, Kotlin lacks this modifier, so encapsulating packages at the syntax level isn’t possible.

Below is an example of a classic Java project layout and the way it relies on the package-private access modifier:

com/example/project/
├── api/
│   ├── PizzaEndpoints.java          (public/package-private)
│
├── domain/
│   ├── pizza/
│   │   ├── PizzaFactory.java        (public) // can be used in kitchen
│   │   ├── Pizza.java               (public) // can be used in kitchen
│   │   ├── DefaultPizzaFactory.java (package-private)
│   │   ├── DoughFactory.java        (package-private)
│   │
│   ├── kitchen/
│   │   ├── KitchenService.java      (package-private)
│
├── infrastructure/
│   ├── DatabaseConfig.java          (package-private)

Kotlin probably left out package-private so as not to create a false sense of security. The modifier doesn’t completely block access from other modules, since members can still be reached if another module uses the same package name. Still, I can’t think of many situations where that would cause real trouble. There’s always some ‘hacky’ way around encapsulation, but that doesn’t mean we ought to use it. In my view, package-private still offers plenty of benefits despite this weakness. It could even be made better than Java’s version by adding safeguards against such bypassing. To learn more, see the issue about providing a package-private visibility modifier and the discussion surrounding it.

Sadly, there’s no simple workaround for this, at least not at the syntax level. Kotlin does have an internal access modifier, but it restricts access at the module level. Creating modules merely to control the visibility of particular class or function declarations would be overkill, particularly when only a handful of them need it. That’s not to say you should avoid dividing your project into modules – on the contrary, it’s frequently a good idea. Even so, finer-grained control over declaration visibility within a module would be preferable. If you still want to enforce package-private access, you could try Konsist (Kotlin’s counterpart to ArchUnit) to write architecture tests that forbid access to non-facade members from other packages. That approach is debatable, though, and clearly not as effective as support built into the syntax.

No union types

Union types let you declare a type standing for one of several entirely unrelated types, without needing inheritance or any other relationship among them. For instance, the function below may return either Error or String:

fun doSomething(): String | Error =  // syntax not supported yet
    if(...) "string" else Error("message")

// this is exhaustive - no `else` required 
val finalResult = when(val result = doSomething()) { 
    is String -> result.doSomething()
    is Error -> handleError(result)
}

As you might guess, this feature lends itself to explicit error handling, a common technique in the functional programming paradigm, which avoids exceptions because they break function purity and make code less predictable.

Sadly, Kotlin doesn’t support union types yet, though sealed classes let you get a similar result, as shown here:

sealed interface Result {
    data class Success(val value: String) : Result
    data class Error(val message: String) : Result
}

fun doSomething(): Result = 
    if(...) Result.Success("string") else Result.Error("message")

// this is exhaustive - no `else` required 
val finalResult = when(val result = doSomething()) { 
    is String -> result.doSomething()
    is Error -> handleError(result)
}

A sealed interface works nicely here, since it guarantees that no other classes can inherit from Result. That constraint can then be used in a when expression to cover every possible case exhaustively.

The biggest drawback of sealed classes is how much code they demand. For error handling, a Result-style interface and its subclasses have to be written from scratch every time you need to model a different set of alternative outcomes of a function. This also makes reusing code considerably harder. Imagine you want to add one extra possible state to the Result type (say, NetworkError alongside FileError) for just a single case. You then have to essentially copy and paste the entire Result class with all of its subclasses and add one more subclass for the new state. Union types would make this far easier:

class ParsingError
class FileError
class Success;

fun doSomething(): ParsingError | Success // syntax error: union types
fun doSomethingElse(): ParsingError | FileError | Success

Another potential workaround is the Either class from Arrow:

fun doSomething(): Either<Success, ParsingError>

Its key weakness is that it supports only two classes, so you still need to write your own classes for errors that are highly specific and hardly reusable. It can also hurt readability because it’s less idiomatic. On top of that, although Arrow is a powerful library, it’s also a complicated beast with considerable overhead, so think very carefully before adopting it in your project. Indeed, Kotlin with Arrow looks nothing like idiomatic Kotlin – it moves toward more functional languages such as Scala. Unless your team has substantial experience with functional programming, I’d advise against this library – for most developers it can make the code much more difficult to follow.

More on the proposal and discussion about union types can be found here. It also suggests a fuller implementation of type intersection, which Kotlin currently supports only to a very limited degree.

No multi-catch block

On the subject of union types… did you know Java actually has a restricted variant of them? They can only be used as catch parameters when handling exceptions. Rather than writing several catch blocks like this:

try {
    // ... throw ...
}
catch (final ClassNotFoundException ex1) {
    // ... body ...
}
catch (final IllegalAccessException ex2) {
    // ... body ...
}

You can write this instead:

try {
    // ... throw ...
} catch (ClassNotFoundException | IllegalAccessException ex) {
    // ...body ...
}

Unfortunately, Kotlin has no support for union types in any form, not even in the catch block.

Kotlin gives you a few ways to get around this. First, where possible, you should probably steer clear of exceptions entirely. If that’s not an option, you might use a construction like this:

try {
    // ...
} catch (e: Exception) {
    when(e) {
        is ClassNotFoundException, is IllegalAccessException -> { /* ... */ }
        else -> throw e
    }
}

Just don’t forget to rethrow any exceptions that don’t match (else -> throw e) so nothing gets swallowed silently. That rethrowing makes the approach less than perfect, but it’s good enough for most situations.

The discussion on adding multi-catch blocks is available in this Kotlin YouTrack issue.

No complex pattern matching

Pattern matching is now a standard part of modern programming languages. Even Java added it in JDK 21 by extending what switch expressions can do. Pattern matching makes code more compact and declarative, which fits functional programming principles nicely. Kotlin offers a powerful when expression for control flow and type checks but doesn’t provide full pattern-matching capabilities like those in languages such as Scala. The expression supports type checks and value comparisons, which makes it merely a more compact alternative to if-else if chains.

Kotlin recently got a small improvement with the arrival of experimental guard conditions in Kotlin 2.1.0, which let you attach additional conditions to when branches:

sealed interface Ingredient {
    data class Tomato(val ripe: Boolean) : Ingredient {
        fun makeSauce() {}
    }

    data class Cheese(val type: String) : Ingredient {
        fun meltCheese() {}
    }
}

fun preparePizza(ingredient: Ingredient) {
    when (ingredient) {
        is Ingredient.Cheese -> ingredient.meltCheese()
        is Ingredient.Tomato if ingredient.ripe -> ingredient.makeSauce()
        else -> println("Unknown ingredient")
    }
}

This is actually very close to the guard patterns Java 21 provides, but in Kotlin it’s still experimental, so you likely shouldn’t rely on it in production code. Looking past Java, languages such as Scala or even Python offer far more advanced pattern matching than Kotlin, chiefly because Kotlin’s when expression doesn’t support destructuring.

The proposal and discussion on pattern matching in Kotlin are in this Kotlin YouTrack issue.

No recursive destructuring declarations

Staying with destructuring, Kotlin supports destructuring declarations really well, as the following examples show:

data class Result(val code: Int, val message: String)
fun doSomething() = Result(5, "OK")

// destructuring works automatically for data classes
val (statusCode, message) = doSomething()

// you can omit the variable name if you don't need it:
val (_, message) = doSomething()

// can be used in loops
val map = mapOf("key" to "value")
for ((key, value) in map) {
    // ...
}

// can be used in lambdas
map.mapValues { (key, value) -> "<$key>$value</$key>" }

Recursive destructuring, however (that is, for nested properties), isn’t supported in Kotlin. For instance, the following won’t work:

data class Person(val name: String, val age: Int)
data class Company(val name: String, val ceo: Person)
fun findCompanies(): Map<String, Company>
findCompanies() // syntax error \/
    .map { (id, (companyName, ceo)) -> "$id: $companyName (CEO: $ceo)" }

I often run into cases where I wish I had this feature, which can be annoying – all the more so because languages like Python have it, and adding it doesn’t look especially difficult. That said, one could argue that if you feel the urge to use recursive destructuring inside a lambda body, you may be trying to do too much in one spot, which risks making your code needlessly complex.

To find out more about the proposal to bring this feature to Koltin, see this Kotlin YouTrack issue. If you believe it would be a worthwhile addition to Kotlin, think about voting for it.

Conclusion

Kotlin is an excellent modern general-purpose programming language that noticeably boosts productivity and makes developers in teams happier 😉. Naturally, nothing is perfect, and there’s always scope for improvement. I chose the features covered in this post based on my own experience with real-world Kotlin projects. Many developers appear to share these pain points, as the large number of votes on YouTrack shows. At the same time, I wouldn’t be surprised if some developers would rather not have these features added, seeing them as unnecessary. Adding features to a programming language is a delicate matter, and language designers shouldn’t implement everything the community asks for, since that would make the language more complex.

Keeping things simple is a valuable feature in its own right.
If you’re interested, more feature requests are listed in this Kotlin YouTrack issue (I’ve already filtered and sorted them for you). If you come across features you’d like the language to have, I strongly encourage you to vote for them. I hope the workarounds described here help you cope with these limitations in your projects (or at least let you share the pain with me). In spite of these small drawbacks, Kotlin is still a pleasure to work with.

Links to feature requests discussed in this post