Skip to Content
Course content

198: What's New in Recent Kotlin Versions

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

Kotlin moves fast. If you've been away from the language for a few months, or if you're still thinking in terms of Kotlin 1.5, you've probably noticed the ecosystem shifting toward the K2 compiler and some very specific syntactic sugar that actually solves real-world annoyances. Instead of listing a changelog, I want to show you how these recent updates change how I actually write code.

We're going to build a tiny "Environment Configuration Manager." It's a common pattern: you need to handle different settings for Dev, Staging, and Production without letting the compiler let you pass a "Production" string into a "Development" function.

Defining Environments with Data Objects

In the past, if I wanted a singleton for my environments, I'd use a standard object. But object has a quirk: its toString() is useless for debugging. You get something like com.example.Env$Dev@5f3a2b. To fix that, I used to have to override toString() manually every single time.

Now, we have data object. It gives us the singleton behavior of an object but the clean string representation and equality checks of a data class. Let's start there:

sealed interface Environment {
    data object Development : Environment
    data object Staging : Environment
    data object Production : Environment
}

I'm using a sealed interface here because it ensures that when I when over my environments later, the compiler will yell at me if I forget to handle one of them.

Type-Safe Keys with Value Classes

One thing I hate is "Stringly-typed" code. Passing a String for a config key is dangerous because you can accidentally pass the value where the key should be. We've had value classes for a bit, but the way the K2 compiler handles them is significantly more efficient and stable now.

I'll wrap my configuration keys in a value class. This gives me type safety at compile time, but at runtime, the JVM just sees a plain String. No extra object allocation overhead.

@JvmInline
value class ConfigKey(val value: String)

class ConfigManager(val env: Environment) {
    private val settings = mutableMapOf<ConfigKey, String>()

    fun set(key: ConfigKey, value: String) {
        settings[key] = value
    }

    fun get(key: ConfigKey): String? = settings[key]
}

Handling the "Singleton State" Mistake

Here is where I usually trip up when I'm moving too fast. I wanted to create a global access point for my config, so I tried to make the ConfigManager a data object too, thinking it would make it easier to log the state of the manager.

// My mistake:
data object GlobalConfig : ConfigManager(Environment.Development) {
    // Wait, this won't work.
}

I immediately hit a compiler error. I forgot that data objects (and objects in general) cannot inherit from a class that requires a constructor argument like ConfigManager(val env: Environment). I was trying to treat a singleton as a subclass of a parameterized class, which is a total logic clash.

To fix this, I'll move the environment dependency into a separate initialization method or just use a standard singleton pattern that holds an instance of the manager. Let's go with a simple object that manages the instance:

object AppConfig {
    lateinit var manager: ConfigManager
    
    fun initialize(env: Environment) {
        manager = ConfigManager(env)
    }
}

Putting it all together in a Main loop

Now we can see the synergy. We have the type safety of the value class, the exhaustiveness of the sealed interface, and the clean logging of the data object. I'll write a quick block to test it:

fun main() {
    val currentEnv = Environment.Staging
    println("Running in: $currentEnv") // Thanks to data object, this prints "Development" not a hash!

    AppConfig.initialize(currentEnv)
    
    val apiKey = ConfigKey("api_key")
    AppConfig.manager.set(apiKey, "secret-12345")
    
    println("Key ${apiKey.value} is set to ${AppConfig.manager.get(apiKey)}")
}

The beauty here is that if I try to pass a raw "api_key" string into AppConfig.manager.get(), the code won't compile. I'm forced to use ConfigKey, which keeps the domain logic explicit.




📋 Practical Task

Implement a Type-Safe Feature Toggle System

Build a small feature toggle system using the patterns discussed in this lesson. Your implementation must include the following:

  • A sealed interface called ToggleState with two data object implementations: Enabled and Disabled.
  • A value class called FeatureId that wraps a String.
  • A class FeatureRegistry that uses a Map to associate FeatureId with ToggleState.
  • A method in FeatureRegistry called isFeatureActive(id: FeatureId): Boolean that returns true only if the state is Enabled.

Test your implementation in a main function by creating a FeatureId("new_ui_layout"), setting it to Enabled, and printing the result of isFeatureActive.

Rating
0 0

There are no comments for now.

to be the first to leave a comment.