What's new in Kotlin 1.6.20
Kotlin 1.6.20 reveals previews of the future language features, makes the hierarchical structure the default for multiplatform projects, and brings evolutionary improvements to other components.
You can also find a short overview of the changes in this video:
In Kotlin 1.6.20, you can try two new language features:
Prototype of context receivers for Kotlin/JVM
With Kotlin 1.6.20, you are no longer limited to having one receiver. If you need more, you can make functions, properties, and classes context-dependent (or contextual) by adding context receivers to their declaration. A contextual declaration does the following:
It requires all declared context receivers to be present in a caller's scope as implicit receivers.
It brings declared context receivers into its body scope as implicit receivers.
To enable context receivers in your project, use the
-Xcontext-receivers compiler option. You can find a detailed description of the feature and its syntax in the KEEP.
Please note that the implementation is a prototype:
-Xcontext-receiversenabled, the compiler will produce pre-release binaries that cannot be used in production code
The IDE support for context receivers is minimal for now
Definitely non-nullable types
To provide better interoperability when extending generic Java classes and interfaces, Kotlin 1.6.20 allows you to mark a generic type parameter as definitely non-nullable on the use site with the new syntax
T & Any. The syntactic form comes from a notation of intersection types and is now limited to a type parameter with nullable upper bounds on the left side of
& and non-nullable
Any on the right side:
Set the language version to
1.7 to enable the feature:
Learn more about definitely non-nullable types in the KEEP.
Kotlin 1.6.20 introduces:
Compatibility improvements of default methods in JVM interfaces: new
@JvmDefaultWithCompatibilityannotation for interfaces and compatibility changes in the
New @JvmDefaultWithCompatibility annotation for interfaces
Kotlin 1.6.20 introduces the new annotation
@JvmDefaultWithCompatibility: use it along with the
-Xjvm-default=all compiler option to create the default method in JVM interface for any non-abstract member in any Kotlin interface.
If there are clients that use your Kotlin interfaces compiled without the
-Xjvm-default=all option, they may be binary-incompatible with the code compiled with this option. Before Kotlin 1.6.20, to avoid this compatibility issue, the recommended approach was to use the
-Xjvm-default=all-compatibility mode and also the
@JvmDefaultWithoutCompatibility annotation for interfaces that didn't need this type of compatibility.
This approach had some disadvantages:
You could easily forget to add the annotation when a new interface was added.
Usually there are more interfaces in non-public parts than in the public API, so you end up having this annotation in many places in your code.
Now, you can use the
-Xjvm-default=all mode and mark interfaces with the
@JvmDefaultWithCompatibility annotation. This allows you to add this annotation to all interfaces in the public API once, and you won't need to use any annotations for new non-public code.
Leave your feedback about this new annotation in this YouTrack ticket.
Compatibility changes in the -Xjvm-default modes
Kotlin 1.6.20 adds the option to compile modules in the default mode (the
-Xjvm-default=disable compiler option) against modules compiled with the
-Xjvm-default=all-compatibility modes. As before, compilations will also be successful if all modules have the
-Xjvm-default=all-compatibility modes. You can leave your feedback in this YouTrack issue.
Kotlin 1.6.20 deprecates the
enable modes of the compiler option
-Xjvm-default. There are changes in other modes' descriptions regarding the compatibility, but the overall logic remains the same. You can check out the updated descriptions.
Support for parallel compilation of a single module in the JVM backend
We are continuing our work to improve the new JVM IR backend compilation time. In Kotlin 1.6.20, we added the experimental JVM IR backend mode to compile all the files in a module in parallel. Parallel compilation can reduce the total compilation time by up to 15%.
Enable the experimental parallel backend mode with the compiler option
-Xbackend-threads. Use the following arguments for this option:
Nis the number of threads you want to use. It should not be greater than your number of CPU cores; otherwise, parallelization stops being effective because of switching context between threads
0to use a separate thread for each CPU core
Gradle can run tasks in parallel, but this type of parallelization doesn't help a lot when a project (or a major part of a project) is just one big task from Gradle's perspective. If you have a very big monolithic module, use parallel compilation to compile more quickly. If your project consists of lots of small modules and has a build parallelized by Gradle, adding another layer of parallelization may hurt performance because of context switching.
Support for callable references to functional interface constructors
Consider the following code:
With callable references to functional interface constructors enabled, this code can be replaced with just a functional interface declaration:
Its constructor will be created implicitly, and any code using the
::Printer function reference will compile. For example:
Preserve the binary compatibility by marking the legacy function
Printer with the
@Deprecated annotation with
Use the compiler option
-XXLanguage:+KotlinFunInterfaceConstructorReference to enable this feature.
Kotlin/Native 1.6.20 marks continued development of its new components. We've taken another step toward consistent experience with Kotlin on other platforms:
An update on the new memory manager
With Kotlin 1.6.20, you can try the Alpha version of the new Kotlin/Native memory manager. It eliminates the differences between the JVM and Native platforms to provide a consistent developer experience in multiplatform projects. For example, you'll have a much easier time creating new cross-platform mobile applications that work on both Android and iOS.
The new Kotlin/Native memory manager lifts restrictions on object-sharing between threads. It also provides leak-free concurrent programming primitives that are safe and don't require any special management or annotations.
The new memory manager will become the default in future versions, so we encourage you to try it now. Check out our blog post to learn more about the new memory manager and explore demo projects, or jump right to the migration instructions to try it yourself.
Try using the new memory manager on your projects to see how it works and share feedback in our issue tracker, YouTrack.
Concurrent implementation for the sweep phase in new memory manager
If you have already switched to our new memory manager, which was announced in Kotlin 1.6, you might notice a huge execution time improvement: our benchmarks show 35% improvement on average. Starting with 1.6.20, there is also a concurrent implementation for the sweep phase available for the new memory manager. This should also improve the performance and decrease the duration of garbage collector pauses.
To enable the feature for the new Kotlin/Native memory manager, pass the following compiler option:
Feel free to share your feedback on the new memory manager performance in this YouTrack issue.
Instantiation of annotation classes
In Kotlin 1.6.0, instantiation of annotation classes became Stable for Kotlin/JVM and Kotlin/JS. The 1.6.20 version delivers support for Kotlin/Native.
Learn more about instantiation of annotation classes.
Interop with Swift async/await: returning Void instead of KotlinUnit
We've continued working on the experimental interop with Swift's async/await (available since Swift 5.5). Kotlin 1.6.20 differs from previous versions in the way it works with
suspend functions with the
Unit return type.
Previously, such functions were presented in Swift as
async functions returning
KotlinUnit. However, the proper return type for them is
Void, similar to non-suspending functions.
To avoid breaking the existing code, we're introducing a Gradle property that makes the compiler translate
Unit-returning suspend functions to
async Swift with the
Void return type:
We plan to make this behavior the default in future Kotlin releases.
Better stack traces with libbacktrace
Kotlin/Native is now able to produce detailed stack traces with file locations and line numbers for better debugging of
This feature uses the libbacktrace library under the hood. Take a look at the following code to see an example of the difference:
1.6.20 with libbacktrace:
On Apple targets, which already had file locations and line numbers in stack traces, libbacktrace provides more details for inline function calls:
1.6.20 with libbacktrace:
To produce better stack traces with libbacktrace, add the following line to
Please tell us how debugging Kotlin/Native with libbacktrace works for you in this YouTrack issue.
Support for standalone Android executables
Previously, Android Native executables in Kotlin/Native were not actually executables but shared libraries that you could use as a NativeActivity. Now there's an option to generate standard executables for Android Native targets.
For that, in the
build.gradle(.kts) part of your project, configure the executable block of your
androidNative target. Add the following binary option:
Note that this feature will become the default in Kotlin 1.7.0. If you want to preserve the current behavior, use the following setting:
Thanks to Mattia Iavarone for the implementation!
We are working hard on Kotlin/Native to speed up the compilation process and improve your developing experience.
Kotlin 1.6.20 brings some performance updates and bug fixes that affect the LLVM IR that Kotlin generates. According to the benchmarks on our internal projects, we achieved the following performance boosts on average:
15% reduction in execution time
20% reduction in the code size of both release and debug binaries
26% reduction in the compilation time of release binaries
These changes also provide a 10% reduction in compilation time for a debug binary on a large internal project.
To achieve this, we've implemented static initialization for some of the compiler-generated synthetic objects, improved the way we structure LLVM IR for every function, and optimized the compiler caches.
Improved error handling during cinterop modules import
This release introduces improved error handling for cases where you import an Objective-C module using the
cinterop tool (as is typical for CocoaPods pods). Previously, if you got an error while trying to work with an Objective-C module (for instance, when dealing with a compilation error in a header), you received an uninformative error message, such as
fatal error: could not build module $name. We expanded upon this part of the
cinterop tool, so you'll get an error message with an extended description.
Support for Xcode 13 libraries
Libraries delivered with Xcode 13 have full support as of this release. Feel free to access them from anywhere in your Kotlin code.
1.6.20 brings the following notable updates to Kotlin Multiplatform:
Hierarchical structure support for multiplatform projects
Kotlin 1.6.20 comes with hierarchical structure support enabled by default. Since introducing it in Kotlin 1.4.0, we've significantly improved the frontend and made IDE import stable.
Previously, there were two ways to add code in a multiplatform project. The first was to insert it in a platform-specific source set, which is limited to one target and can't be reused by other platforms. The second is to use a common source set shared across all the platforms that are currently supported by Kotlin.
Now you can share source code among several similar native targets that reuse a lot of the common logic and third-party APIs. The technology will provide the correct default dependencies and find the exact API available in the shared code. This eliminates a complex build setup and having to use workarounds to get IDE support for sharing source sets among native targets. It also helps prevent unsafe API usages meant for a different target.
The technology will come in handy for library authors, too, as a hierarchical project structure allows them to publish and consume libraries with common APIs for a subset of targets.
By default, libraries published with the hierarchical project structure are compatible only with hierarchical structure projects. Learn more about project-library compatibility.
Better code-sharing in your project
Without hierarchical structure support, there is no straightforward way to share code across some but not all Kotlin targets. One popular example is sharing code across all iOS targets and having access to iOS-specific dependencies, like
Thanks to the hierarchical project structure support, you can now achieve this out of the box. In the new structure, source sets form a hierarchy. You can use platform-specific language features and dependencies available for each target that a given source set compiles to.
For example, consider a typical multiplatform project with two targets —
iosX64 for iOS devices and simulators. The Kotlin tooling understands that both targets have the same function and allows you to access that function from the intermediate source set,
The Kotlin toolchain provides the correct default dependencies, like Kotlin/Native stdlib or native libraries. Moreover, Kotlin tooling will try its best to find exactly the API surface area available in the shared code. This prevents such cases as, for example, the use of a macOS-specific function in code shared for Windows.
More opportunities for library authors
When a multiplatform library is published, the API of its intermediate source sets is now properly published alongside it, making it available for consumers. Again, the Kotlin toolchain will automatically figure out the API available in the consumer source set while carefully watching out for unsafe usages, like using an API meant for the JVM in JS code. Learn more about sharing code in libraries.
Configuration and setup
Starting with Kotlin 1.6.20, all your new multiplatform projects will have a hierarchical project structure. No additional setup is required.
If you've already turned it on manually, you can remove the deprecated options from
gradle.properties:# gradle.properties kotlin.mpp.enableGranularSourceSetsMetadata=true kotlin.native.enableDependencyPropagation=false // or 'true', depending on your previous setup
For Kotlin 1.6.20, we recommend using Android Studio 2021.1.1 (Bumblebee) or later to get the best experience.
You can also opt-out. To disable hierarchical structure support, set the following options in
gradle.properties:# gradle.properties kotlin.mpp.hierarchicalStructureSupport=false
Leave your feedback
This is a significant change to the whole ecosystem. We would appreciate your feedback to help make it even better.
Try it now and report any difficulties you encounter to our issue tracker.
Kotlin CocoaPods Gradle plugin
To simplify CocoaPods integration, Kotlin 1.6.20 delivers the following features:
The CocoaPods plugin now has tasks that build XCFrameworks with all registered targets and generate the Podspec file. This can be useful when you don't want to integrate with Xcode directly, but you want to build artifacts and deploy them to your local CocoaPods repository.
Learn more about building XCFrameworks.
If you use CocoaPods integration in your projects, you're used to specifying the required Pod version for the entire Gradle project. Now you have more options:
Specify the Pod version directly in the
Continue using a Gradle project version
If none of these properties is configured, you'll get an error.
You can now configure the CocoaPod name in the
cocoapodsblock instead of changing the name of the whole Gradle project.
The CocoaPods plugin introduces a new
extraSpecAttributesproperty, which you can use to configure properties in a Podspec file that were previously hard-coded, like
See the full Kotlin CocoaPods Gradle plugin DSL reference.
Kotlin/JS improvements in 1.6.20 mainly affect the IR compiler:
Incremental compilation for development binaries with IR compiler
To make Kotlin/JS development with the IR compiler more efficient, we're introducing a new incremental compilation mode.
When building development binaries with the
compileDevelopmentExecutableKotlinJs Gradle task in this mode, the compiler caches the results of previous compilations on the module level. It uses the cached compilation results for unchanged source files during subsequent compilations, making them complete more quickly, especially with small changes. Note that this improvement exclusively targets the development process (shortening the edit-build-debug cycle) and doesn't affect the building of production artifacts.
To enable incremental compilation for development binaries, add the following line to the project's
In our test projects, the new mode made incremental compilation up to 30% faster. However, the clean build in this mode became slower because of the need to create and populate the caches.
Please tell us what you think of using incremental compilation with your Kotlin/JS projects in this YouTrack issue.
Lazy initialization of top-level properties by default with IR compiler
In Kotlin 1.4.30, we presented a prototype of lazy initialization of top-level properties in the JS IR compiler. By eliminating the need to initialize all properties when the application launches, lazy initialization reduces the startup time. Our measurements showed about a 10% speed-up on a real-life Kotlin/JS application.
Now, having polished and properly tested this mechanism, we're making lazy initialization the default for top-level properties in the IR compiler.
If for some reason you need to initialize a property eagerly (upon the application start), mark it with the
Separate JS files for project modules by default with IR compiler
Previously, the JS IR compiler offered an ability to generate separate
.js files for project modules. This was an alternative to the default option – a single
.js file for the whole project. This file might be too large and inconvenient to use, because whenever you want to use a function from your project, you have to include the entire JS file as a dependency. Having multiple files adds flexibility and decreases the size of such dependencies. This feature was available with the
-Xir-per-module compiler option.
Starting from 1.6.20, the JS IR compiler generates separate
.js files for project modules by default.
Compiling the project into a single
.js file is now available with the following Gradle property:
In previous releases, the experimental per-module mode (available via the
-Xir-per-module=true flag) invoked
main() functions in each module. This is inconsistent with the regular single
.js mode. Starting with 1.6.20, the
main() function will be invoked in the main module only in both cases. If you do need to run some code when a module is loaded, you can use top-level properties annotated with the
@EagerInitialization annotation. See Lazy initialization of top-level properties by default (IR).
Char class optimization
Char class is now handled by the Kotlin/JS compiler without introducing boxing (similar to inline classes). This speeds up operations on chars in Kotlin/JS code.
Aside from the performance improvement, this changes the way
Improvements to export and TypeScript declaration generation
Kotlin 1.6.20 is bringing multiple fixes and improvements to the export mechanism (the
@JsExport annotation), including the generation of TypeScript declarations (
.d.ts). We've added the ability to export interfaces and enums, and we've fixed the export behavior in some corner cases that were reported to us previously. For more details, see the list of export improvements in YouTrack.
@AfterTest guarantees for asynchronous tests
Kotlin 1.6.20 makes
@AfterTest functions work properly with asynchronous tests on Kotlin/JS. If a test function's return type is statically resolved to
Promise, the compiler now schedules the execution of the
@AfterTest function to the corresponding
Kotlin 1.6.20 introduces a couple of features to improve the security of your code:
Using relative paths in klibs
A library in
klib format contains a serialized IR representation of source files, which also includes their paths for generating proper debug information. Before Kotlin 1.6.20, stored file paths were absolute. Since the library author may not want to share absolute paths, the 1.6.20 version comes with an alternative option.
If you are publishing a
klib and want to use only relative paths of source files in the artifact, you can now pass the
-Xklib-relative-path-base compiler option with one or multiple base paths of source files:
Persisting yarn.lock for Kotlin/JS Gradle projects
The Kotlin/JS Gradle plugin now provides an ability to persist the
yarn.lock file, making it possible to lock the versions of the npm dependencies for your project without additional Gradle configuration. The feature brings changes to the default project structure by adding the auto-generated
kotlin-js-store directory to the project root. It holds the
yarn.lock file inside.
We strongly recommend committing the
kotlin-js-store directory and its contents to your version control system. Committing lockfiles to your version control system is a recommended practice because it ensures your application is being built with the exact same dependency tree on all machines, regardless of whether those are development environments on other machines or CI/CD services. Lockfiles also prevent your npm dependencies from being silently updated when a project is checked out on a new machine, which is a security concern.
Tools like Dependabot can also parse the
yarn.lock files of your Kotlin/JS projects, and provide you with warnings if any npm package you depend on is compromised.
If needed, you can change both directory and lockfile names in the build script:
Installation of npm dependencies with --ignore-scripts by default
The Kotlin/JS Gradle plugin now prevents the execution of lifecycle scripts during the installation of npm dependencies by default. The change is aimed at reducing the likelihood of executing malicious code from compromised npm packages.
To roll back to the old configuration, you can explicitly enable lifecycle scripts execution by adding the following lines to
Learn more about npm dependencies of a Kotlin/JS Gradle project.
Kotlin 1.6.20 brings the following changes for the Kotlin Gradle Plugin:
compilerExecutionStrategyfor defining a Kotlin compiler execution strategy
Properties for defining Kotlin compiler execution strategy
Before Kotlin 1.6.20, you used the system property
-Dkotlin.compiler.execution.strategy to define a Kotlin compiler execution strategy. This property might have been inconvenient in some cases. Kotlin 1.6.20 introduces a Gradle property with the same name,
kotlin.compiler.execution.strategy, and the compile task property
The system property still works, but it will be removed in future releases.
The current priority of properties is the following:
The task property
compilerExecutionStrategytakes priority over the system property and the Gradle property
The Gradle property takes priority over the system property.
There are three compiler execution strategies that you can assign to these properties:
Where Kotlin compiler is executed
Inside its own daemon process
The default strategy. Can be shared between different Gradle daemons
Inside the Gradle daemon process
May share the heap with the Gradle daemon
Out of process
In a separate process for each call
Accordingly, the available values for
kotlin.compiler.execution.strategy properties (both system and Gradle's) are:
Use the Gradle property
The available values for the
compilerExecutionStrategy task property are:
Use the task property
compilerExecutionStrategy in the
build.gradle.kts build script:
Please leave your feedback in this YouTrack task.
Deprecation of build options for kapt and coroutines
In Kotlin 1.6.20, we changed deprecation levels of the properties:
We deprecated the ability to run kapt via the Kotlin daemon with
kapt.use.worker.api– now it produces a warning to Gradle's output. By default, kapt has been using Gradle workers since the 1.3.70 release, and we recommend sticking to this method.
We are going to remove the option
kapt.use.worker.apiin future releases.
We deprecated the
kotlin.experimental.coroutinesGradle DSL option and the
kotlin.coroutinesproperty used in
gradle.properties. Just use suspending functions or add the
kotlinx.coroutinesdependency to your
Learn more about coroutines in the Coroutines guide.
Removal of the kotlin.parallel.tasks.in.project build option
In Kotlin 1.5.20, we announced the deprecation of the build option
kotlin.parallel.tasks.in.project. This option has been removed in Kotlin 1.6.20.
Depending on the project, parallel compilation in the Kotlin daemon may require more memory. To reduce memory consumption, increase the heap size for the Kotlin daemon.
Learn more about the currently supported compiler options in the Kotlin Gradle plugin.