What’s New in Kotlin 1.4.0

In Kotlin 1.4.0, we ship a number of improvements in all of its components, with the focus on quality and performance. Below you will find the list of the most important changes in Kotlin 1.4.0.

Language features and improvements

New tools in the IDE

New compiler

Kotlin/JVM

Kotlin/JS

Kotlin/Native

Kotlin Multiplatform

Gradle project improvements

Standard library

Stable JSON serialization

Scripting and REPL

Migrating to Kotlin 1.4.0

Language features and improvements

Kotlin 1.4.0 comes with a variety of different language features and improvements. They include:

SAM conversions for Kotlin interfaces

Before Kotlin 1.4.0, you could apply SAM (Single Abstract Method) conversions only when working with Java methods and Java interfaces from Kotlin. From now on, you can use SAM conversions for Kotlin interfaces as well. To do so, mark a Kotlin interface explicitly as functional with the fun modifier.

SAM conversion applies if you pass a lambda as an argument when an interface with only one single abstract method is expected as a parameter. In this case, the compiler automatically converts the lambda to an instance of the class that implements the abstract member function.

1. fun interface IntPredicate {
2. fun accept(i: Int): Boolean
3. }

5. val isEven = IntPredicate { it % 2 == 0 }

7. fun main() {
8. println("Is 7 even? - ${isEven.accept(7)}")
9. }

Learn more about Kotlin functional interfaces and SAM conversions.

Explicit API mode for library authors

Kotlin compiler offers explicit API mode for library authors. In this mode, the compiler performs additional checks that help make the library’s API clearer and more consistent. It adds the following requirements for declarations exposed to the library’s public API:

  • Visibility modifiers are required for declarations if the default visibility exposes them to the public API. This helps ensure that no declarations are exposed to the public API unintentionally.
  • Explicit type specifications are required for properties and functions that are exposed to the public API. This guarantees that API users are aware of the types of API members they use.

Depending on your configuration, these explicit APIs can produce errors (strict mode) or warnings (warning mode). Certain kinds of declarations are excluded from such checks for the sake of readability and common sense:

  • primary constructors
  • properties of data classes
  • property getters and setters
  • override methods

Explicit API mode analyzes only the production sources of a module.

To compile your module in the explicit API mode, add the following lines to your Gradle build script:

1. kotlin {
2. // for strict mode
3. explicitApi()
4. // or
5. explicitApi = 'strict'

7. // for warning mode
8. explicitApiWarning()
9. // or
10. explicitApi = 'warning'
11. }
1. kotlin {
2. // for strict mode
3. explicitApi()
4. // or
5. explicitApi = ExplicitApiMode.Strict

7. // for warning mode
8. explicitApiWarning()
9. // or
10. explicitApi = ExplicitApiMode.Warning
11. }

When using the command-line compiler, switch to explicit API mode by adding the -Xexplicit-api compiler option with the value strict or warning.

1. -Xexplicit-api={strict|warning}

For more details about the explicit API mode, see the KEEP.

Mixing named and positional arguments

In Kotlin 1.3, when you called a function with named arguments, you had to place all the arguments without names (positional arguments) before the first named argument. For example, you could call f(1, y = 2), but you couldn’t call f(x = 1, 2).

It was really annoying when all the arguments were in their correct positions but you wanted to specify a name for one argument in the middle. It was especially helpful for making absolutely clear which attribute a boolean or null value belongs to.

In Kotlin 1.4, there is no such limitation – you can now specify a name for an argument in the middle of a set of positional arguments. Moreover, you can mix positional and named arguments any way you like, as long as they remain in the correct order.

1. fun reformat(
2. str: String,
3. uppercaseFirstLetter: Boolean = true,
4. wordSeparator: Char = ' '
5. ) {
6. // ...
7. }

9. //Function call with a named argument in the middle
10. reformat("This is a String!", uppercaseFirstLetter = false , '-')

Trailing comma

With Kotlin 1.4 you can now add a trailing comma in enumerations such as argument and parameter lists, when entries, and components of destructuring declarations. With a trailing comma, you can add new items and change their order without adding or removing commas.

This is especially helpful if you use multi-line syntax for parameters or values. After adding a trailing comma, you can then easily swap lines with parameters or values.

1. fun reformat(
2. str: String,
3. uppercaseFirstLetter: Boolean = true,
4. wordSeparator: Character = ' ', //trailing comma
5. ) {
6. // ...
7. }
1. val colors = listOf(
2. "red",
3. "green",
4. "blue", //trailing comma
5. )

Callable reference improvements

Kotlin 1.4 supports more cases for using callable references:

  • References to functions with default argument values
  • Function references in Unit-returning functions
  • References that adapt based on the number of arguments in a function
  • Suspend conversion on callable references

References to functions with default argument values

Now you can use callable references to functions with default argument values. If the callable reference to the function foo takes no arguments, the default value 0 is used.

1. fun foo(i: Int = 0): String = "$i!"

3. fun apply(func: () -> String): String = func()

5. fun main() {
6. println(apply(::foo))
7. }

Previously, you had to write additional overloads for the function apply to use the default argument values.

1. // some new overload
2. fun applyInt(func: (Int) -> String): String = func(0)

Function references in Unit-returning functions

In Kotlin 1.4, you can use callable references to functions returning any type in Unit-returning functions. Before Kotlin 1.4, you could only use lambda arguments in this case. Now you can use both lambda arguments and callable references.

1. fun foo(f: () -> Unit) { }
2. fun returnsInt(): Int = 42

4. fun main() {
5. foo { returnsInt() } // this was the only way to do it  before 1.4
6. foo(::returnsInt) // starting from 1.4, this also works
7. }

References that adapt based on the number of arguments in a function

Now you can adapt callable references to functions when passing a variable number of arguments (vararg) . You can pass any number of parameters of the same type at the end of the list of passed arguments.

1. fun foo(x: Int, vararg y: String) {}

3. fun use0(f: (Int) -> Unit) {}
4. fun use1(f: (Int, String) -> Unit) {}
5. fun use2(f: (Int, String, String) -> Unit) {}

7. fun test() {
8. use0(::foo)
9. use1(::foo)
10. use2(::foo)
11. }

Suspend conversion on callable references

In addition to suspend conversion on lambdas, Kotlin now supports suspend conversion on callable references starting from version 1.4.0.

1. fun call() {}
2. fun takeSuspend(f: suspend () -> Unit) {}

4. fun test() {
5. takeSuspend { call() } // OK before 1.4
6. takeSuspend(::call) // In Kotlin 1.4, it also works
7. }

Using break and continue inside when expressions included in loops

In Kotlin 1.3, you could not use unqualified break and continue inside when expressions included in loops. The reason was that these keywords were reserved for possible fall-through behavior in when expressions.

That’s why if you wanted to use break and continue inside when expressions in loops, you had to label them, which became rather cumbersome.

1. fun test(xs: List<Int>) {
2. LOOP@for (x in xs) {
3. when (x) {
4. 2 -> continue@LOOP
5. 17 -> break@LOOP
6. else -> println(x)
7. }
8. }
9. }

In Kotlin 1.4, you can use break and continue without labels inside when expressions included in loops. They behave as expected by terminating the nearest enclosing loop or proceeding to its next step.

1. fun test(xs: List<Int>) {
2. for (x in xs) {
3. when (x) {
4. 2 -> continue
5. 17 -> break
6. else -> println(x)
7. }
8. }
9. }

The fall-through behavior inside when is subject to further design.

Back to top

New tools in the IDE

With Kotlin 1.4, you can use the new tools in IntelliJ IDEA to simplify Kotlin development:

New flexible Project Wizard

With the flexible new Kotlin Project Wizard, you have a place to easily create and configure different types of Kotlin projects, including multiplatform projects, which can be difficult to configure without a UI.

Kotlin Project Wizard – Multiplatform project

The new Kotlin Project Wizard is both simple and flexible:

  1. Select the project template, depending on what you’re trying to do. More templates will be added in the future.
  2. Select the build system – Gradle (Kotlin or Groovy DSL), Maven, or IntelliJ IDEA. The Kotlin Project Wizard will only show the build systems supported on the selected project template.
  3. Preview the project structure directly on the main screen.

Then you can finish creating your project or, optionally, configure the project on the next screen:

  1. Add/remove modules and targets supported for this project template.
  2. Configure module and target settings, for example, the target JVM version, target template, and test framework.

Kotlin Project Wizard - Configure targets

In the future, we are going to make the Kotlin Project Wizard even more flexible by adding more configuration options and templates.

You can try out the new Kotlin Project Wizard by working through these tutorials:

Coroutine Debugger

Many people already use coroutines for asynchronous programming. But when it came to debugging, working with coroutines before Kotlin 1.4, could be a real pain. Since coroutines jumped between threads, it was difficult to understand what a specific coroutine was doing and check its context. In some cases, tracking steps over breakpoints simply didn’t work. As a result, you had to rely on logging or mental effort to debug code that used coroutines.

In Kotlin 1.4, debugging coroutines is now much more convenient with the new functionality shipped with the Kotlin plugin.

Debugging works for versions 1.3.8 or later of kotlinx-coroutines-core.

The Debug Tool Window now contains a new Coroutines tab. In this tab, you can find information about both currently running and suspended coroutines. The coroutines are grouped by the dispatcher they are running on.

Debugging coroutines

Now you can:

  • Easily check the state of each coroutine.
  • See the values of local and captured variables for both running and suspended coroutines.
  • See a full coroutine creation stack, as well as a call stack inside the coroutine. The stack includes all frames with variable values, even those that would be lost during standard debugging.

If you need a full report containing the state of each coroutine and its stack, right-click inside the Coroutines tab, and then click Get Coroutines Dump. Currently, the coroutines dump is rather simple, but we’re going to make it more readable and helpful in future versions of Kotlin.

Coroutines Dump

Learn more about debugging coroutines in this blog post and IntelliJ IDEA documentation.

Back to top

New compiler

The new Kotlin compiler is going to be really fast; it will unify all the supported platforms and provide an API for compiler extensions. It’s a long-term project, and we’ve already completed several steps in Kotlin 1.4.0:

New more powerful type inference algorithm

Kotlin 1.4 uses a new, more powerful type inference algorithm. This new algorithm was already available to try in Kotlin 1.3 by specifying a compiler option, and now it’s used by default. You can find the full list of issues fixed in the new algorithm in YouTrack. Here you can find some of the most noticeable improvements:

More cases where type is inferred automatically

The new inference algorithm infers types for many cases where the old algorithm required you to specify them explicitly. For instance, in the following example the type of the lambda parameter it is correctly inferred to String?:

1. //sampleStart
2. val rulesMap: Map<String, (String?) -> Boolean> = mapOf(
3. "weak" to { it != null },
4. "medium" to { !it.isNullOrBlank() },
5. "strong" to { it != null && "^[a-zA-Z0-9]+$".toRegex().matches(it) }
6. )
7. //sampleEnd

9. fun main() {
10. println(rulesMap.getValue("weak")("abc!"))
11. println(rulesMap.getValue("strong")("abc"))
12. println(rulesMap.getValue("strong")("abc!"))
13. }

In Kotlin 1.3, you needed to introduce an explicit lambda parameter or replace to with a Pair constructor with explicit generic arguments to make it work.

Smart casts for a lambda’s last expression

In Kotlin 1.3, the last expression inside a lambda wasn’t smart cast unless you specified the expected type. Thus, in the following example, Kotlin 1.3 infers String? as the type of the result variable:

1. val result = run {
2. var str = currentValue()
3. if (str == null) {
4. str = "test"
5. }
6. str // the Kotlin compiler knows that str is not null here
7. }
8. // The type of 'result' is String? in Kotlin 1.3 and String in Kotlin 1.4

In Kotlin 1.4, thanks to the new inference algorithm, the last expression inside a lambda gets smart cast, and this new, more precise type is used to infer the resulting lambda type. Thus, the type of the result variable becomes String.

In Kotlin 1.3, you often needed to add explicit casts (either !! or type casts like as String) to make such cases work, and now these casts have become unnecessary.

Smart casts for callable references

In Kotlin 1.3, you couldn’t access a member reference of a smart cast type. Now in Kotlin 1.4 you can:

1. import kotlin.reflect.KFunction

3. sealed class Animal
4. class Cat : Animal() {
5. fun meow() {
6. println("meow")
7. }
8. }

10. class Dog : Animal() {
11. fun woof() {
12. println("woof")
13. }
14. }

16. //sampleStart
17. fun perform(animal: Animal) {
18. val kFunction: KFunction<*> = when (animal) {
19. is Cat -> animal::meow
20. is Dog -> animal::woof
21. }
22. kFunction.call()
23. }
24. //sampleEnd

26. fun main() {
27. perform(Cat())
28. }

You can use different member references animal::meow and animal::woof after the animal variable has been smart cast to specific types Cat and Dog. After type checks, you can access member references corresponding to subtypes.

Better inference for delegated properties

The type of a delegated property wasn’t taken into account while analyzing the delegate expression which follows the by keyword. For instance, the following code didn’t compile before, but now the compiler correctly infers the types of the old and new parameters as String?:

1. import kotlin.properties.Delegates

3. fun main() {
4. var prop: String? by Delegates.observable(null) { p, old, new ->
5. println("$old → $new")
6. }
7. prop = "abc"
8. prop = "xyz"
9. }

SAM conversion for Java interfaces with different arguments

Kotlin has supported SAM conversions for Java interfaces from the beginning, but there was one case that wasn’t supported, which was sometimes annoying when working with existing Java libraries. If you called a Java method that took two SAM interfaces as parameters, both arguments needed to be either lambdas or regular objects. You couldn’t pass one argument as a lambda and another as an object.

The new algorithm fixes this issue, and you can pass a lambda instead of a SAM interface in any case, which is the way you’d naturally expect it to work.

1. // FILE: A.java
2. public class A {
3. public static void foo(Runnable r1, Runnable r2) {}
4. }
1. // FILE: test.kt
2. fun test(r1: Runnable) {
3. A.foo(r1) {}  // Works in Kotlin 1.4
4. }

Java SAM interfaces in Kotlin

In Kotlin 1.4, you can use Java SAM interfaces in Kotlin and apply SAM conversions to them.

1. import java.lang.Runnable

3. fun foo(r: Runnable) {}

5. fun test() {
6. foo { } // OK
7. }

In Kotlin 1.3, you would have had to declare the function foo above in Java code to perform a SAM conversion.

Unified backends and extensibility

In Kotlin, we have three backends that generate executables: Kotlin/JVM, Kotlin/JS, and Kotlin/Native. Kotlin/JVM and Kotlin/JS don’t share much code since they were developed independently of each other. Kotlin/Native is based on a new infrastructure built around an intermediate representation (IR) for Kotlin code.

We are now migrating Kotlin/JVM and Kotlin/JS to the same IR. As a result, all three backends share a lot of logic and have a unified pipeline. This allows us to implement most features, optimizations, and bug fixes only once for all platforms. Both new IR-based back-ends are in Alpha.

A common backend infrastructure also opens the door for multiplatform compiler extensions. You will be able to plug into the pipeline and add custom processing and transformations that will automatically work for all platforms.

We encourage you to use our new JVM IR and JS IR backends, which are currently in Alpha, and share your feedback with us.

Back to top

Kotlin/JVM

Kotlin 1.4.0 includes a number of JVM-specific improvements, such as:

New JVM IR backend

Along with Kotlin/JS, we are migrating Kotlin/JVM to the unified IR backend, which allows us to implement most features and bug fixes once for all platforms. You will also be able to benefit from this by creating multiplatform extensions that will work for all platforms.

Kotlin 1.4.0 does not provide a public API for such extensions yet, but we are working closely with our partners, including Jetpack Compose, who are already building their compiler plugins using our new backend.

We encourage you to try out the new Kotlin/JVM backend, which is currently in Alpha, and to file any issues and feature requests to our issue tracker. This will help us to unify the compiler pipelines and bring compiler extensions like Jetpack Compose to the Kotlin community more quickly.

To enable the new JVM IR backend, specify an additional compiler option in your Gradle build script:

1. kotlinOptions.useIR = true

If you enable Jetpack Compose, you will automatically be opted in to the new JVM backend without needing to specify the compiler option in kotlinOptions.

When using the command-line compiler, add the compiler option -Xuse-ir.

You can use code compiled by the new JVM IR backend only if you’ve enabled the new backend. Otherwise, you will get an error. Considering this, we don’t recommend that library authors switch to the new backend in production.

New modes for generating default methods

When compiling Kotlin code to targets JVM 1.8 and above, you could compile non-abstract methods of Kotlin interfaces into Java’s default methods. For this purpose, there was a mechanism that includes the @JvmDefault annotation for marking such methods and the -Xjvm-default compiler option that enables processing of this annotation.

In 1.4.0, we’ve added a new mode for generating default methods: -Xjvm-default=all compiles all non-abstract methods of Kotlin interfaces to default Java methods. For compatibility with the code that uses the interfaces compiled without default, we also added all-compatibility mode.

For more information about default methods in the Java interop, see the documentation and this blog post.

Unified exception type for null checks

Starting from Kotlin 1.4.0, all runtime null checks will throw a java.lang.NullPointerException instead of KotlinNullPointerException, IllegalStateException, IllegalArgumentException, and TypeCastException. This applies to: the !! operator, parameter null checks in the method preamble, platform-typed expression null checks, and the as operator with a non-null type. This doesn’t apply to lateinit null checks and explicit library function calls like checkNotNull or requireNotNull.

This change increases the number of possible null check optimizations that can be performed either by the Kotlin compiler or by various kinds of bytecode processing tools, such as the Android R8 optimizer.

Note that from a developer’s perspective, things won’t change that much: the Kotlin code will throw exceptions with the same error messages as before. The type of exception changes, but the information passed stays the same.

Type annotations in the JVM bytecode

Kotlin can now generate type annotations in the JVM bytecode (target version 1.8+), so that they become available in Java reflection at runtime. To emit the type annotation in the bytecode, follow these steps:

  1. Make sure that your declared annotation has a proper annotation target (Java’s ElementType.TYPE_USE or Kotlin’s AnnotationTarget.TYPE) and retention (AnnotationRetention.RUNTIME).
  2. Compile the annotation class declaration to JVM bytecode target version 1.8+. You can specify it with -jvm-target=1.8 compiler option.
  3. Compile the code that uses the annotation to JVM bytecode target version 1.8+ (-jvm-target=1.8) and add the -Xemit-jvm-type-annotations compiler option.

Note that the type annotations from the standard library aren’t emitted in the bytecode for now because the standard library is compiled with the target version 1.6.

So far, only the basic cases are supported:

  • Type annotations on method parameters, method return types and property types;
  • Invariant projections of type arguments, such as Smth<@Ann Foo>, Array<@Ann Foo>.

In the following example, the @Foo annotation on the String type can be emitted to the bytecode and then used by the library code:

1. @Target(AnnotationTarget.TYPE)
2. annotation class Foo

4. class A {
5. fun foo(): @Foo String = "OK"
6. }

Back to top

Kotlin/JS

On the JS platform, Kotlin 1.4.0 provides the following improvements:

New Gradle DSL

The kotlin.js Gradle plugin comes with an adjusted Gradle DSL, which provides a number of new configuration options and is more closely aligned to the DSL used by the kotlin-multiplatform plugin. Some of the most impactful changes include:

  • Explicit toggles for the creation of executable files via binaries.executable(). Read more about the executing Kotlin/JS and its environment here.
  • Configuration of webpack’s CSS and style loaders from within the Gradle configuration via cssSupport. Read more about using them here.
  • Improved management for npm dependencies, with mandatory version numbers or semver version ranges, as well as support for development, peer, and optional npm dependencies using devNpm, optionalNpm and peerNpm. Read more about dependency management for npm packages directly from Gradle here.
  • Stronger integrations for Dukat, the generator for Kotlin external declarations. External declarations can now be generated at build time, or can be manually generated via a Gradle task. Read more about how to use the integration here.

New JS IR backend

The IR backend for Kotlin/JS, which currently has Alpha stability, provides some new functionality specific to the Kotlin/JS target which is focused around the generated code size through dead code elimination, and improved interoperation with JavaScript and TypeScript, among others.

To enable the Kotlin/JS IR backend, set the key kotlin.js.compiler=ir in your gradle.properties, or pass the IR compiler type to the js function of your Gradle build script:

1. kotlin {
2. js(IR) { // or: LEGACY, BOTH
3. // . . .
4. }
5. binaries.executable()
6. }

For more detailed information about how to configure the Kotlin/JS IR compiler backend, check out the documentation.

With the new @JsExport annotation and the ability to generate TypeScript definitions from Kotlin code, the Kotlin/JS IR compiler backend improves JavaScript & TypeScript interoperability. This also makes it easier to integrate Kotlin/JS code with existing tooling, to create hybrid applications and leverage code-sharing functionality in multiplatform projects.

Learn more about the available features in the Kotlin/JS IR compiler backend in the documentation.

Back to top

Kotlin/Native

In 1.4.0, Kotlin/Native got a significant number of new features and improvements, including:

Support for Kotlin’s suspending functions in Swift and Objective-C

In 1.4.0, we add the basic support for suspending functions in Swift and Objective-C. Now, when you compile a Kotlin module into an Apple framework, suspending functions are available in it as functions with callbacks (completionHandler in the Swift/Objective-C terminology). When you have such functions in the generated framework’s header, you can call them from your Swift or Objective-C code and even override them.

For example, if you write this Kotlin function:

1. suspend fun queryData(id: Int): String = ...

…then you can call it from Swift like so:

1. queryData(id: 17) { result, error in
2. if let e = error {
3. print("ERROR: \(e)")
4. } else {
5. print(result!)
6. }
7. }

For more information about using suspending functions in Swift and Objective-C, see the documentation.

Objective-C generics support by default

Previous versions of Kotlin provided experimental support for generics in Objective-C interop. Since 1.4.0, Kotlin/Native generates Apple frameworks with generics from Kotlin code by default. In some cases, this may break existing Objective-C or Swift code calling Kotlin frameworks. To have the framework header written without generics, add the -Xno-objc-generics compiler option.

1. kotlin {
2. targets.withType<org.jetbrains.kotlin.gradle.plugin.mpp.KotlinNativeTarget> {
3. binaries.all {
4. freeCompilerArgs += "-Xno-objc-generics"
5. }
6. }
7. }

Please note that all specifics and limitations listed in the documentation are still valid.

Exception handling in Objective-C/Swift interop

In 1.4.0, we slightly change the Swift API generated from Kotlin with respect to the way exceptions are translated. There is a fundamental difference in error handling between Kotlin and Swift. All Kotlin exceptions are unchecked, while Swift has only checked errors. Thus, to make Swift code aware of expected exceptions, Kotlin functions should be marked with a @Throws annotation specifying a list of potential exception classes.

When compiling to Swift or the Objective-C framework, functions that have or are inheriting @Throws annotation are represented as NSError*-producing methods in Objective-C and as throws methods in Swift.

Previously, any exceptions other than RuntimeException and Error were propagated as NSError. Now this behavior changes: now NSError is thrown only for exceptions that are instances of classes specified as parameters of @Throws annotation (or their subclasses). Other Kotlin exceptions that reach Swift/Objective-C are considered unhandled and cause program termination.

Generate release .dSYMs on Apple targets by default

Starting with 1.4.0, the Kotlin/Native compiler produces debug symbol files (.dSYMs) for release binaries on Darwin platforms by default. This can be disabled with the -Xadd-light-debug=disable compiler option. On other platforms, this option is disabled by default. To toggle this option in Gradle, use:

1. kotlin {
2. targets.withType<org.jetbrains.kotlin.gradle.plugin.mpp.KotlinNativeTarget> {
3. binaries.all {
4. freeCompilerArgs += "-Xadd-light-debug={enable|disable}"
5. }
6. }
7. }

For more information about crash report symbolication, see the documentation.

Performance improvements

Kotlin/Native has received a number of performance improvements that speed up both the development process and execution. Here are some examples:

  • To improve the speed of object allocation, we now offer the mimalloc memory allocator as an alternative to the system allocator. mimalloc works up to two times faster on some benchmarks. Currently, the usage of mimalloc in Kotlin/Native is experimental; you can switch to it using the -Xallocator=mimalloc compiler option.
  • We’ve reworked how C interop libraries are built. With the new tooling, Kotlin/Native produces interop libraries up to 4 times as fast as before, and artifacts are 25% to 30% the size they used to be.
  • Overall runtime performance has improved because of optimizations in GC. This improvement will be especially apparent in projects with a large number of long-lived objects. HashMap and HashSet collections now work faster by escaping redundant boxing.
  • In 1.3.70 we introduced two new features for improving the performance of Kotlin/Native compilation: caching project dependencies and running the compiler from the Gradle daemon. Since that time, we’ve managed to fix numerous issues and improve the overall stability of these features.

Simplified management of CocoaPods dependencies

Previously, once you integrated your project with the dependency manager CocoaPods, you could build an iOS, macOS, watchOS, or tvOS part of your project only in Xcode, separate from other parts of your multiplatform project. These other parts could be built in Intellij IDEA.

Moreover, every time you added a dependency on an Objective-C library stored in CocoaPods (Pod library), you had to switch from IntelliJ IDEA to Xcode, call pod install, and run the Xcode build there.

Now you can manage Pod dependencies right in Intellij IDEA while enjoying the benefits it provides for working with code, such as code highlighting and completion. You can also build the whole Kotlin project with Gradle, without having to switch to Xcode. This means you only have to go to Xcode when you need to write Swift/Objective-C code or run your application on a simulator or device.

Now you can also work with Pod libraries stored locally.

Depending on your needs, you can add dependencies between:

  • A Kotlin project and Pod libraries stored remotely in the CocoaPods repository or stored locally on your machine.
  • A Kotlin Pod (Kotlin project used as a CocoaPods dependency) and an Xcode project with one or more targets.

Complete the initial configuration, and when you add a new dependency to cocoapods, just re-import the project in IntelliJ IDEA. The new dependency will be added automatically. No additional steps are required.

Learn how to add dependencies.

Back to top

Kotlin Multiplatform

Multiplatform projects are in Alpha. Language features and tooling may change in future Kotlin versions.

Kotlin Multiplatform reduces time spent writing and maintaining the same code for different platforms while retaining the flexibility and benefits of native programming. We continue investing our effort in multiplatform features and improvements:

Multiplatform projects require Gradle 6.0 or later.

Sharing code in several targets with the hierarchical project structure

With the new hierarchical project structure support, you can share code among several platforms in a multiplatform project.

Previously, any code added to a multiplatform project could be placed either in a platform-specific source set, which is limited to one target and can’t be reused by any other platform, or in a common source set, like commonMain or commonTest, which is shared across all the platforms in the project. In the common source set, you could only call a platform-specific API by using an expect declaration that needs platform-specific actual implementations.

This made it easy to share code on all platforms, but it was not so easy to share between only some of the targets, especially similar ones that could potentially reuse a lot of the common logic and third-party APIs.

For example, in a typical multiplatform project targeting iOS, there are two iOS-related targets: one for iOS ARM64 devices, and the other for the x64 simulator. They have separate platform-specific source sets, but in practice, there is rarely a need for different code for the device and simulator, and their dependencies are much alike. So iOS-specific code could be shared between them.

Apparently, in this setup, it would be desirable to have a shared source set for two iOS targets, with Kotlin/Native code that could still directly call any of the APIs that are common to both the iOS device and the simulator.

Code shared for iOS targets

Now you can do this with the hierarchical project structure support, which infers and adapts the API and language features available in each source set based on which targets consume them.

For common combinations of targets, you can create a hierarchical structure with target shortcuts.

For example, create two iOS targets and the shared source set shown above with the ios() shortcut:

1. kotlin {
2. ios() // iOS device and simulator targets; iosMain and iosTest source sets
3. }

For other combinations of targets, create a hierarchy manually by connecting the source sets with the dependsOn relation.

Hierarchical structure

1. kotlin {
2. sourceSets {
3. desktopMain {
4. dependsOn(commonMain)
5. }
6. linuxX64Main {
7. dependsOn(desktopMain)
8. }
9. mingwX64Main {
10. dependsOn(desktopMain)
11. }
12. macosX64Main {
13. dependsOn(desktopMain)
14. }
15. }
16. }

``` 1. kotlin{ 2. sourceSets { 3. val desktopMain by creating { 4. dependsOn(commonMain) 5. } 6. val linuxX64Main by getting { 7. dependsOn(desktopMain) 8. } 9. val mingwX64Main by getting { 10. dependsOn(desktopMain) 11. } 12. val macosX64Main by getting { 13. dep

(本文超出站点单文档体积上限,已截断)