Estimate project
← All posts

Kotlin Levels Up: What 2.2 Brings

Want to know which Kotlin 2.2 features are stable enough for production, what has changed in the language itself rather than just the tooling, or which features could influence the way you write and organize Kotlin code? Then this article is exactly what you need.

15 min read
KotlinProgramming LanguagesKotlinServerSide

Each Kotlin release comes with a changelog that usually blends two kinds of changes: small, incremental improvements you hardly notice, and the ones that genuinely change your everyday work. Kotlin 2.2 follows this pattern precisely. If you’ve been keeping a close eye on how the language evolves, you’ll likely recall features such as non-local returns or enhanced string interpolation showing up in preview mode. In Kotlin 2.2, several of them have at last become stable, together with a handful of new additions to the language and the compiler. Others, such as context parameters, are still experimental but deserve attention, particularly if you build libraries or DSLs, or like to play with more advanced Kotlin features.

This brief overview concentrates on precisely those changes that are likely to make a difference in real-world Kotlin projects - no hype, no abstract debates about language design, just the practical bits.

Who is this blog post for?

This article is aimed at developers who work with Kotlin every day (be it writing backend services or building libraries), or who try Kotlin out in side projects.

If you’re asking yourself:

  • Which Kotlin 2.2 features are stable enough for production?
  • What has changed in the language itself, not just in the tooling?
  • Which features could influence the way you write or organize your Kotlin code?

then this post should give you the answers without diving too deeply into compiler internals or the philosophy of language design. If Kotlin is entirely new to you, it may be better to begin somewhere else - we won’t explain basic syntax and will instead concentrate on what has changed since Kotlin 2.1.

Prerequisites

Before going through the features, it helps to make clear what’s stable and what still needs an explicit opt-in. Some language features added in Kotlin 2.2 are now stable and ready for production. Others, in particular experimental ones such as context parameters, still have to be turned on through compiler options. To try these features out, make sure your build is set up properly.

For instance, with Gradle:

// build.gradle.kts

kotlin {
   compilerOptions {
       freeCompilerArgs.add("-Xcontext-parameters")
   }
}

Which feature name you need depends on the particular experimental feature you want to test, and we’ll mention it in the corresponding sections. Let’s begin with the features that are finally stable.

Out of experimental: what Kotlin 2.2 makes stable

Several language features from earlier Kotlin releases started out as experimental, which meant you could test them, but there was no guarantee they wouldn’t change. Kotlin 2.2 promotes a few of them to stable status, so they’re ready for production and no longer need special compiler flags.

Below is a short summary of what became stable in Kotlin 2.2.

More sensible default methods on the JVM

For Kotlin projects targeting the JVM, Kotlin 2.2 brings a subtle yet important change to how default method implementations in interfaces are treated. It may impact both your bytecode and binary compatibility. From this release onward, unless you configure it differently, Kotlin emits default methods directly in interfaces, in line with the modern Java approach.

This supersedes the old workaround in which Kotlin generated extra DefaultImpls classes that held default implementations under the hood. For most developers, the generated bytecode gets simpler and Kotlin behaves more like Java developers would expect. At the same time, you need to watch out for possible compatibility problems, particularly when mixing Kotlin and Java in one project, or when unrelated supertypes declare clashing default implementations.

This behavior is controlled by the new stable jvmDefault compiler option, which supersedes the older -Xjvm-default flag, now deprecated, for example:

// build.gradle.kts

kotlin {
   compilerOptions {
       jvmDefault = JvmDefaultMode.ENABLE
   }
}

JvmDefaultMode offers the following options:

  • Enable - the default in Kotlin 2.2. Default methods are emitted directly in interfaces, while compatibility bridges and DefaultImpls classes are still generated to keep binary compatibility with older Kotlin or Java code.
  • No-compatibility - emits only the default methods in interfaces, without the extra compatibility classes: a sensible choice for new codebases that don’t have to support older Kotlin versions.
  • Disable - turns off default methods in interfaces entirely, going back to the pre-2.2 Kotlin behavior with DefaultImpls only.

The default setting suits most projects and makes the generated bytecode simpler. However, if you maintain libraries, care about compatibility, or work in codebases mixing Kotlin and Java, it’s a good idea to verify which option fits you best.

Non-local break/continue has become stable

Using break and continue across non-local scopes, for instance inside lambdas, is now a stable feature.

Improved string templates with multiple dollars

Producing templates or DSLs that need $ symbols used to be awkward. In Kotlin 2.2, multi-dollar string interpolation becomes stable.

Smarter conditions in when expressions

Writing expressive, readable when expressions has simply become easier. Kotlin 2.2 makes guard conditions stable, so you can add extra conditions straight to individual branches.

Still in the oven: experimental and beta features worth a try

Not all of Kotlin 2.2 is ready for production. Some of the newly added features are flagged as experimental: you can experiment with them, but they may be altered or dropped in later versions. To try them, you have to turn them on explicitly through compiler options.

For instance, context parameters require adding the -Xcontext-parameters argument to your build configuration, as demonstrated in the Prerequisites section. Here’s what Kotlin 2.2 offers to anyone ready to venture past the stable boundary.

Context parameters: passing dependencies without the clutter

Kotlin 2.2 introduces context parameters, a language feature that makes it simpler to pass contextual information through code. If you’ve ever had to thread the same objects – database connections, user details, or feature flags – through several layers of functions, you know how fast that bloats method signatures.

With context parameters, you can state these requirements in a tidier, more structured manner, without falling back on global state or passing dependencies around by hand. They can be applied to functions and properties to declare that certain objects must be present in the surrounding scope. Inside the function or property body, these objects are implicitly accessible, with no need to pass them as explicit parameters.

For functions, the syntax is as follows:

interface Dependency {
   fun doSomething()
}

interface OtherDependency {
   fun doSomethingElse()
}

context(dependency: Dependency, otherDependency: OtherDependency)
fun someFunction() {
   // dependency and otherDependency are available implicitly
   dependency.doSomething()
   otherDependency.doSomethingElse()
}

And here’s what the context syntax looks like for properties:

interface Config {
   fun isEnabled(feature: String): Boolean
}

context(config: Config)
val isFeatureEnabled: Boolean
   get() = config.isEnabled("someFeature")

This feature keeps your code tidy in cases where explicitly passing dependencies would make function signatures needlessly long. It’s a handy solution when you want configuration, feature flags, or technical services to be available inside a function or computed property without spreading them across every layer of your code.

Context parameters let you state these requirements explicitly, precisely where they’re relevant and nowhere else. For now, context parameters work only with functions and properties. As the feature is still experimental, what it can do may change in upcoming Kotlin releases.

Here’s a more realistic example taken from a multi-layered system:

interface UserContext {
   fun currentUser(): String
   fun hasRole(role: String): Boolean
}

interface FeatureFlags {
   fun isEnabled(feature: String): Boolean
}

interface TransactionManager {
   fun <T> inTransaction(fn: () -> T): T
}

class AccountFacade(
   private val transactionManager: TransactionManager,
   private val accountDeletionService: AccountDeletionService
) {
   context(_: UserContext, _: FeatureFlags)
   fun deleteAccount(accountId: String) {
       transactionManager.inTransaction {
           accountDeletionService.deleteAccount(accountId)
       }
   }
}

class AccountDeletionService {

   context(featureFlags: FeatureFlags)
   private val isDeleteAccountEnabled: Boolean
       get() = featureFlags.isEnabled("deleteAccount")

   context(userContext: UserContext, featureFlags: FeatureFlags)
   fun deleteAccount(accountId: String) {
       if (isDeleteAccountEnabled) {
           ensureAdmin()
           // perform account deletion logic
           println("Account $accountId deleted by user ${userContext.currentUser()}.")
       } else {
           throw FeatureDisabledException("Account deletion is not enabled.")
       }
   }

   context(userContext: UserContext)
   private fun ensureAdmin() {
       require(userContext.hasRole("ADMIN")) {
           "User ${userContext.currentUser()} does not have ADMIN role."
       }
   }
}

In this example:

  • The UserContext and FeatureFlags dependencies are available precisely where they are required.
  • There’s no need to pass these dependencies by hand through every function call.
  • Context parameters spell out what each function needs in order to be called, without depending on global state or hidden magic.
  • You’ll also spot the underscore (_) used for unnamed context parameters, which are needed for resolution but aren’t accessed directly. This lets the compiler pass them along without adding unused names to the scope. It’s useful when you hand dependencies down to further calls without using them yourself. You can see it at work in the AccountFacade.deleteAccount(accountId: String) method, where UserContext and FeatureFlags are both declared as unnamed context parameters with _.

With this pattern, it’s easier to build layered systems that have explicit boundaries and clean function signatures, particularly when dealing with technical concerns such as security, configuration or feature toggles. Here’s what calling such a function looks like in practice: you supply the required context objects once, and every function relying on them can use them implicitly.

Below is an example showing how this pattern makes things simpler in practice:

val userContext = object : UserContext {
   override fun currentUser() = "john.doe"
   override fun hasRole(role: String) = role == "ADMIN"
}

val featureFlags = object : FeatureFlags {
   override fun isEnabled(feature: String) = feature == "deleteAccount"
}

val transactionManager = object : TransactionManager {
   override fun <T> inTransaction(fn: () -> T): T = fn()
}

val accountFacade = AccountFacade(
   transactionManager = transactionManager,
   accountDeletionService = AccountDeletionService()
)

context(userContext, featureFlags) {
   accountFacade.deleteAccount("12345")
}

This pattern allows you to establish the context a single time and then call functions without repeatedly passing the same objects. Your code stays readable and free of boilerplate, particularly in systems sharing common contextual dependencies.

Smarter type-driven resolution for tidier code

Kotlin 2.2 brings context-sensitive resolution, an experimental feature that makes working with enums, sealed classes, and object declarations easier whenever the compiler already knows the expected type. Until now, even when the context made the type perfectly clear, you still had to spell out the full name of enum constants or sealed class members. With context-sensitive resolution, the compiler relies on type information from the surrounding code to resolve those names for you, so the code becomes shorter and less repetitive. To try it out, you need to add the -Xcontext-sensitive-resolution argument to the compiler configuration.

Below is a quick comparison of working with enums before and with context-sensitive resolution turned on. Here’s what it looks like today without context-sensitive resolution:

enum class BinaryDigit {
   ONE,
   ZERO,
}

fun toInt(binaryDigit: BinaryDigit): Int = when (binaryDigit) {
   BinaryDigit.ONE -> 1
   BinaryDigit.ZERO -> 0
}

fun fromInt(value: Int): BinaryDigit = when (value) {
   1 -> BinaryDigit.ONE
   0 -> BinaryDigit.ZERO
   else -> throw IllegalArgumentException("Invalid binary digit value: $value")
}

And here’s the same when expression with context-sensitive resolution turned on:

fun toInt(binaryDigit: BinaryDigit): Int = when (binaryDigit) {
   ONE -> 1
   ZERO -> 0
}

fun fromInt(value: Int): BinaryDigit = when (value) {
   1 -> ONE
   0 -> ZERO
   else -> throw IllegalArgumentException("Invalid binary digit value: $value")
}

The first thing you’ll probably notice is that, with context-sensitive resolution, the explicit BinaryDigit qualifier is no longer required for enum constants inside the when expression. The code gets noticeably shorter, easier to read, and less repetitive. But the feature does more than simplify enum usage. By making use of the surrounding type context, the Kotlin compiler now resolves names better in many typical scenarios. In particular, it takes into account expected types coming from arguments, return types, declarations, and similar constructs to resolve names automatically.

Consequently, the following language features gain from it:

  • conditions in when expressions whose subject type is known
  • type checks with is
  • return statements, both implicit and explicit
  • equality checks such as == and !=
  • assignments and initializations
  • function calls with expected argument types.

To sum this feature up briefly: context-sensitive resolution lets the compiler automatically resolve the names of enum entries, sealed class members, and object declarations using the expected type from the surrounding context. It removes the need for repeated fully-qualified names and makes the code clearer, all while keeping type safety intact.

No more duplicated annotations thanks to @all

Annotating properties in Kotlin can turn out trickier than it seems. The reason is that one val or var declaration frequently maps to several elements under the hood: the field, the getter, the setter, and even the constructor parameter when declared in a primary constructor. To make your custom annotation apply to all of them, you used to have to enumerate every possible target by hand, for example:

@Target(
   AnnotationTarget.FIELD,
   AnnotationTarget.PROPERTY,
   AnnotationTarget.PROPERTY_GETTER,
   AnnotationTarget.PROPERTY_SETTER,
   AnnotationTarget.VALUE_PARAMETER
)
annotation class HexColor

Kotlin 2.2 lets you simplify this with the new experimental @all meta-target. You annotate a property a single time, and the annotation is applied automatically to all of the property’s relevant parts. What difference does that make in practice? Let’s quickly compare how properties used to be annotated with how the @all meta-target simplifies it

Before Kotlin 2.2 - repetitive, manual annotation of every target:

data class Square(
   @field:HexColor
   @property:HexColor
   @get:HexColor
   @param:HexColor
   val backgroundColor: String
) {
   @field:HexColor
   @property:HexColor
   @get:HexColor
   @set:HexColor
   var borderColor: String = backgroundColor
}

In Kotlin 2.2, using the @all meta-target, the code above can be reduced to:

data class Square(
   // applies @HexColor to field, property, get, param and set - depending if it's var
   @all:HexColor
   val backgroundColor: String
) {
   // applies @HexColor to field, property, get and set
   // param is not applicable here since it's not a constructor parameter
   @all:HexColor
   var borderColor: String = backgroundColor
}

@all guarantees that the annotation is applied consistently to every relevant part of the property, so you don’t have to repeat yourself across targets such as fields, getters, or constructor parameters. This comes in particularly handy for custom annotations used for validation, serialization, or code generation.

In our example, your validation logic or a compile-time tool could later process @HexColor to check that color values match the expected HEX format.

Because @all is experimental in Kotlin 2.2, it has to be enabled explicitly in your project. To do that, add the -Xannotation-target-all compiler option the same way as described in the Prerequisties section above.

Keep helper types where they belong with nested type aliases

If you’ve ever built a Kotlin DSL, you’ve quite likely reached for typealias to tidy up some ugly generic signatures. And if you did that in a reusable builder class, you probably wanted those aliases to live inside the class rather than cluttering the top-level namespace. Kotlin 2.2 at last allows this.

Thanks to the new support for nested type aliases, type aliases can now be declared inside classes, objects, or interfaces, provided the alias doesn’t implicitly capture a type parameter of the enclosing declaration. Apart from that limitation, the feature gives you far more freedom in structuring internal APIs and DSLs. Let’s look at a practical example. Imagine you’re writing a lightweight validation DSL:

typealias Predicate<T> = (T) -> Boolean
typealias Rule<T> = Pair<String, Predicate<T>>
typealias Error = String
typealias Validator<T> = (T) -> List<Error>

class ValidatorBuilder<T> {
   private val rules = mutableListOf<Rule<T>>()

   fun rule(error: Error, predicate: Predicate<T>) {
       rules += error to predicate
   }

   fun build(): Validator<T> = { value ->
       rules.filterNot { (_, predicate) -> predicate(value) }
           .map { (msg, _) -> msg }
   }
}

This works, but every type alias sits at the top level. The package gets more crowded, and implementation details that matter only inside the builder are exposed. Kotlin 2.2 lets you tidy this up:

class ValidatorBuilder<T> {
   typealias Predicate<T> = (T) -> Boolean
   typealias Rule<T> = Pair<String, Predicate<T>>
   typealias Error = String
   typealias Validator<T> = (T) -> List<Error>

   private val rules = mutableListOf<Rule<T>>()

   fun rule(error: Error, predicate: Predicate<T>) {
       rules += error to predicate
   }

   fun build(): Validator<T> = { value ->
       rules.filterNot { (_, predicate) -> predicate(value) }
           .map { (msg, _) -> msg }
   }
}

Now everything is scoped to the place where it’s really used. Internal names no longer leak out needlessly. Autocompletion gets more relevant, the file is easier to find your way around, and your code becomes more consistent. Keep in mind that nested type aliases can’t implicitly reference type parameters from the enclosing scope.

When your alias relies on a generic, it has to be declared explicitly:

class ValidatorBuilder<T> {
   // Not allowed – captures T implicitly
   // typealias Predicate = (T) -> Boolean

   // Allowed – declares T directly
   typealias Predicate<T> = (T) -> Boolean
}

A few rules are worth remembering:

  • All the usual typealias rules still apply.
  • They can’t be more visible than the types they alias.
  • They’re scoped like nested classes, so they may shadow outer aliases
  • If necessary, you can mark them internal or private.
  • They aren’t supported in expect/actual declarations in Kotlin Multiplatform.

It’s a minor change that makes your code feel more deliberate: less noise, more structure. That trade-off is well worth it. As the feature is still in beta, you have to turn it on by hand by adding the -Xnested-type-aliases argument to the compiler arguments, as explained earlier in the Prerequisties section.

Closing thoughts on Kotlin 2.2

Kotlin 2.2 may not make headlines, but it pays to look closely. A few long-awaited features, such as non-local control flow and guard conditions in when, have finally become stable. Others, such as context parameters, smarter name resolution, or the new @all meta-target, signal a language that keeps getting more expressive and ergonomic.

Even the more specialized changes, like nested type aliases or the adjustments to JVM method generation, show that the Kotlin team keeps listening to what developers actually need and questions old defaults whenever that makes sense.

Whether you’re writing production code, designing DSLs, or simply keeping your tooling up to date, Kotlin 2.2 offers meaningful improvements that are worth a look. And if Kotlin is completely new to you, this is a pretty good moment to jump in.