Kotlin Reference
Kotlin Reference
Kotlin docs 47
Is anything missing? 52
Multiplatform programming 53
Use cases 58
What's next? 59
Sample projects 59
Supported platforms 60
Sample projects 60
Videos 60
Community 60
Security 61
Next steps 62
Kotlin/JS frameworks 65
2
Get started with Kotlin/JS 67
Kotlin Native 67
Why Kotlin/Native? 68
Target platforms 68
Interoperability 68
How to start 69
Sample projects 69
Interactive editors 70
Libraries 72
Learning Kotlin 77
Language features 78
Kotlin/JVM 83
Kotlin/Native 84
Kotlin Multiplatform 87
Kotlin/JS 89
Gradle 90
Standard library 93
Serialization 1.3.0-RC 97
3
What's new in Kotlin 1.5.20 97
Kotlin/JVM 98
Kotlin/Native 100
Kotlin/JS 101
Gradle 102
Kotlin/JVM 106
Kotlin/Native 109
Kotlin/JS 110
Kotlin/JVM 126
Kotlin/Native 127
Kotlin/JS 127
Kotlin/Native 131
Contracts 132
4
Capturing when subject in a variable 134
@JvmDefault 137
Tooling 140
Tools 149
JavaScript 150
5
Kotlin 1.5.20 for KMM 164
Functions 177
Variables 178
6
Creating classes and instances 178
Comments 179
Ranges 182
Collections 183
Idioms 186
7
Execute a statement if null 190
if expression 191
Formatting 197
Numbers 214
Booleans 221
8
Characters 222
Strings 222
Arrays 224
If expression 229
Exceptions 236
Imports 239
9
Classes 240
Constructors 240
Inheritance 244
Inheritance 245
Properties 249
Interfaces 253
10
Visibility modifiers 257
Packages 257
Modules 259
Extensions 259
Copying 266
Variance 269
11
Inner classes 276
Members 279
Inheritance 280
Representation 280
Delegation 287
Functions 297
12
Tail recursive functions 303
noinline 312
Equality 330
13
Structural equality 331
Threading 333
Callbacks 334
Coroutines 335
Coroutines 336
Annotations 337
Usage 338
Constructors 338
Lambdas 339
Reflection 345
14
JVM dependency 345
Tutorials 353
Enjoy the results – update the logic only once 403
15
Examples 408
Transactions 431
Concurrency 439
Atomics 446
16
Low-level capabilities 449
Coroutines 450
Samples 454
FAQ 458
Be supportive 465
17
Targets 469
Compilations 471
18
Publish a multiplatform library 496
Summary 507
Targets 518
Compilations 529
Dependencies 532
19
Language settings 534
Operators 558
20
Inheritance from Java classes 559
Properties 561
Visibility 568
KClass 568
Null-safety 570
Create a RESTful web service with a database using Spring Boot – tutorial 572
21
Execute HTTP requests 580
22
Create an application 598
Run the application 600
Dependencies 607
CSS 613
Yarn 614
Troubleshooting 615
23
Exclude declarations from DCE 632
Convert JS- and React-related classes and interfaces to external interfaces 637
24
JavaScript modules
650
Browser targets 651
Example 655
25
Concurrency in Kotlin/Native 667
Workers 667
Examples 675
26
Bindings 687
27
Read C Strings in Kotlin 714
Usage 721
Mappings 721
Subclassing 728
C features 728
Unsupported 728
28
Produce binaries with debug info with Kotlin/Native compiler 751
Breakpoints 751
Stepping 753
29
KMM plugin releases 769
Update to the new release 770
Copy 788
Iterators 790
Range 793
Progression 794
Sequences 795
Construct 796
30
Sequence processing example 797
Map 802
Zip 802
Associate 803
Flatten 805
Partition 808
Grouping 810
Slice 811
Chunked 812
Windowed 812
31
Check element existence 816
Ordering 817
Filter 833
Distinctions 838
Functions 842
32
takeIf and takeUnless 845
Timeout 862
33
Async-style functions 868
Buffering 895
34
Launching flow 910
Flow and Reactive Streams 913
Channels 914
Pipelines 916
Fan-out 918
Fan-in 920
CoroutineExceptionHandler 925
Supervision 929
Actors 938
35
Selecting from channels 940
Serialization 956
Libraries 957
Formats 957
Gradle 965
36
Configuring dependencies 968
OSGi 981
Maven 983
Dependencies 983
OSGi 989
Ant 990
37
Targeting JavaScript with single source folder and metaInfo option 992
References 992
REPL 996
Differences between "Kotlin coding conventions" and "IntelliJ IDEA default code style" 998
38
Gradle 1018
Maven 1019
Gradle 1022
Maven 1022
Gradle 1024
Maven 1024
39
Supported annotations 1032
Gradle 1032
Maven 1033
Overview 1035
Resources 1037
Limitations 1043
Types 1046
Misc 1047
40
Details 1048
AnnotationValue 1049
Element 1049
ExecutableElement 1049
Parameterizable 1050
QualifiedNameable 1050
TypeElement 1050
TypeParameterElement 1051
VariableElement 1051
ArrayType 1051
DeclaredType 1052
ExecutableType 1052
IntersectionType 1052
TypeMirror 1052
TypeVariable 1053
WildcardType 1053
Elements 1053
Types 1054
Example 1 1056
Example 2 1057
Advanced 1060
41
Frequently asked questions 1060
Maven 1068
Gradle 1068
FAQ 1068
FAQ 1074
42
Is Kotlin an object-oriented language or a functional one? 1075
What advantages does Kotlin give me over the Java programming language? 1075
Install the EAP Plugin for IntelliJ IDEA or Android Studio 1080
43
Configure your build for EAP 1082
Contribution 1085
Libraries 1090
Tools 1107
44
Compatibility guide for Kotlin 1.4 1108
Tools 1129
Scope 1144
Structure 1145
Scope 1147
Classification 1151
45
Usage guidelines 1155
How can I get more involved with the Kotlin community? 1156
Security 1157
46
Kotlin
docs
Get started with Kotlin What's new in Kotlin
You can get started with Kotlin using an online editor. If Discover what features are available in the newest Kotlin
you already have an IDE or you are ready to install one, release. You can try out upcoming features in the preview
here are also some ways to begin using Kotlin on your versions before they are released.
local machine.
What's new in Kotlin 1.5.30
Get started with Kotlin
What's new in Kotlin plugin 2021.2
Try Kotlin online
Kotlin public roadmap
Get started with KMM in Android Studio
KMM plugin releases for Android Studio
Acquaint yourself with some of the concepts and the Find a way to learn Kotlin that works for you. There are lots
basics of Kotlin. of learning materials available from our team and other
authors.
Basic syntax
Kotlin by example
Basic types
Kotlin Koans
Control flow
Kotlin Basics track on JetBrains Academy
Null safety
Hands-on tutorials
Coroutines
EduTools in IntelliJ IDEA
Coding conventions
Books
47
Kotlin YouTube Channel Stay in touch and contribute
Our YouTube channel is packed with resources for learning If you are interested in what's going with Kotlin, join us on
Kotlin! Subscribe to stay updated for shows, the latest social media, and get involved.
news, and live events!
Contribute to Kotlin
Kotlin in Spring Framework
Participate in Early Access Program
Webinars with Experts
Join Kotlin Slack
Kotlin Multiplatform Multiverse
Follow Kotlin on Twitter
Competitive Programming
Chat on Reddit
Kotlin Standard Library
Participate in Stack Overflow discussions
Talking Kotlin Podcast
Get
started
with
Kotlin
Kotlin is a modern but already mature programming language aimed to make developers happier. It’s concise, safe,
interoperable with Java and other languages, and provides many ways to reuse code between multiple platforms for
productive programming.
Learn
Kotlin
fundamentals
If you're already familiar with one or more programming languages and want to learn Kotlin, start with these Kotlin
learning materials.
If Kotlin is your first programming language, we recommend starting with the Atomic Kotlin book or signing up for the
free Kotlin Basics track on JetBrains Academy.
Create
your
powerful
application
with
Kotlin
Backend app
Here is how you can take the first steps in developing Kotlin server-side applications.
48
1. Install the latest version of IntelliJ IDEA.
To start from scratch, create a basic JVM application with the IntelliJ IDEA project wizard.
If you prefer more robust examples, choose one of the frameworks below and create a project:
Spring Ktor
A mature family of frameworks with an established ecosystem A lightweight framework for those who value freedom in making
that is used by millions of developers worldwide. architectural decisions.
Create a RESTful web service with Spring Boot. Create HTTP APIs with Ktor.
Build web applications with Spring Boot and Kotlin. Create a WebSocket chat with Ktor.
Use Spring Boot with Kotlin and RSocket. Create an interactive website with Ktor.
3. Use Kotlin and third-party libraries in your application. Learn more about adding library and tool dependencies to your project.
The Kotlin standard library offers a lot of useful things such as collections or coroutines.
Take a look at the following third-party frameworks, libs and tools for Kotlin.
Slack: get an invite and join the #getting-started, #server, #spring, or #ktor channels.
6. Follow Kotlin on Twitter, Reddit, and Youtube, and don't miss any important ecosystem updates.
Here you'll learn how to develop and improve your cross-platform mobile application usingKotlin Multiplatform Mobile (KMM).
To start from scratch, create a basic KMM application with the project wizard.
If you have an existing Android application and want to make it cross-platform, complete theMake your Android application work
on iOS tutorial.
If you prefer real-life examples, clone and play with an existing project, for example the networking and data storage project from
the hands-on tutorial or any KMM sample.
3. Use a wide set of multiplatform libraries to implement the required business logic only once in the shared module. Learn more about
adding dependencies.
49
Library Details
Ktor Docs.
DateTime Docs.
Learn how KMM is used at Netflix, VWWare, Yandex, and many other companies.
Slack: get an invite and join the #getting-started and #multiplatform channels.
6. Follow Kotlin on Twitter, Reddit, and Youtube, and don't miss any important ecosystem updates.
Kotlin provides an ability to transpile your Kotlin code, the Kotlin standard library, and any compatible dependencies to JavaScript.
Here you'll learn how to develop and improve your frontend web application usingKotlin/JS.
To start from scratch, create a basic browser application with the IntelliJ IDEA project wizard.
If you prefer more robust examples, complete the Building Web Applications with React and Kotlin/JS hands-on tutorial. It
includes a sample project that can serve as a good starting point for your own projects, and contains useful snippets and
templates.
50
Library Details
kotlinx.browser The Kotlin library for accessing browser-specific functionality, including typical top-level objects such as
document and window.
kotlinx.html The Kotlin library for generating DOM elements using statically-typed HTML builders.
fritz2 A third-party lightweight, high-performance, independent library for building reactive web apps in Kotlin
that are heavily dependent on coroutines and flows.
Doodle A third-party vector-based UI framework that uses browser's capabilities to draw user interfaces.
Compose for Web, a The JetBrains framework that brings Google's Jetpack Compose UI toolkit to the browser (currently with
part of Compose Alpha stability).
Multiplatform
kotlin-wrappers Provide convenient abstractions and deep integrations for one of the most popular JavaScript frameworks.
Kotlin wrappers also provide support for a number of adjacent technologies like react-redux, react-router,
or styled-components.
Slack: get an invite and join the #getting-started and #javascript channels.
6. Follow Kotlin on Twitter, Reddit, and Youtube, and don't miss any important ecosystem updates.
Android app
If you want to start using Kotlin for Android development, readGoogle’s recommendation for getting started with Kotlin on
Android.
If you're new to Android and want to learn to create applications with Kotlin, check outthis Udacity course.
Follow Kotlin on Twitter, Reddit, and Youtube, and don't miss any important ecosystem updates.
51
Multiplatform library
Support for multiplatform programming is one of Kotlin’s key benefits. It reduces time spent writing and maintaining the same code
for different platforms while retaining the flexibility and benefits of native programming.
If you prefer more robust examples, complete the Create and publish a multiplatform library tutorial. It shows how to create a
multiplatform library for JVM, JS, and Native platforms, test it and publish to a local Maven repository.
3. Use libraries in your application. Learn more about adding dependencies on libraries.
Library Details
Coroutines Docs.
DateTime Docs.
Slack: get an invite and join the #getting-started and #multiplatform channels.
6. Follow Kotlin on Twitter, Reddit, and Youtube, and don't miss any important ecosystem updates.
Is
anything
missing?
52
If anything is missing or seems confusing on this page, please share your feedback.
Multiplatform
programming
Multiplatform projects are in Alpha. Language features and tooling may change in future Kotlin versions.
Support for multiplatform programming is one of Kotlin’s key benefits. It reduces time spent writing and maintaining
the same code for different platforms while retaining the flexibility and benefits of native programming.
53
Kotlin Multiplatform
Common Kotlin includes the language, core libraries, and basic tools. Code written in common Kotlin works
everywhere on all platforms.
With Kotlin Multiplatform libraries, you can reuse the multiplatform logic in common and platform-specific code.
Common code can rely on a set of libraries that cover everyday tasks such as HTTP, serialization, and managing
coroutines.
To interop with platforms, use platform-specific versions of Kotlin. Platform-specific versions of Kotlin (Kotlin/JVM,
Kotlin/JS, Kotlin/Native) include extensions to the Kotlin language, and platform-specific libraries and tools.
54
Through these platforms you can access the platform native code (JVM, JS, and Native) and leverage all native
capabilities.
With Kotlin Multiplatform, spend less time on writing and maintaining the same code for different platforms – just share
it using the mechanisms Kotlin provides:
Share code among all platforms used in your project. Use it for sharing the common business logic that applies to all
platforms.
Share code among some platforms included in your project but not all. Do this when you can reuse much of the code
in similar platforms.
55
Hierarchical structure
56
Code shared for iOS targets
If you need to access platform-specific APIs from the shared code, use the Kotlin mechanism of expected and actual
declarations.
With this mechanism, a common source set defines an expected declaration, and platform source sets must provide the
actual declaration that corresponds to the expected declaration. This works for most Kotlin declarations, such as
functions, classes, interfaces, enumerations, properties, and annotations.
57
Expect and actual declarations
//Common
expect fun randomUUID(): String
//Android
import java.util.*
actual fun randomUUID() = UUID.randomUUID().toString()
//iOS
import platform.Foundation.NSUUID
actual fun randomUUID(): String = NSUUID().UUIDString()
Use
cases
Android
—
iOS
Sharing code between mobile platforms is one of the major Kotlin Multiplatform use cases. With Kotlin Multiplatform
Mobile (KMM), you can build multiplatform mobile applications sharing code, such as business logic, connectivity, and
more, between Android and iOS.
58
Client
—
Server
Another scenario when code sharing may bring benefits is a connected application where the logic can be reused on both
the server and the client side running in the browser. This is covered by Kotlin Multiplatform as well.
The Ktor framework is suitable for building asynchronous servers and clients in connected systems.
What's
next?
New to Kotlin? Visit Getting started with Kotlin.
Documentation
Get started with Kotlin Multiplatform Mobile (KMM)
Tutorials
Create your first KMM application shows how to create a mobile application that works on Android and iOS with the
help of the KMM plugin for Android Studio. Create, run, and test your first multiplatform mobile application.
Creating a multiplatform Kotlin library teaches how to create a multiplatform library available for JVM, JS, and Native
and which can be used from any other common code (for example, shared with Android and iOS). It also shows how to
write tests which will be executed on all platforms and use an efficient implementation provided by a specific platform.
Building a full stack web app with Kotlin Multiplatform teaches the concepts behind building an application that targets
Kotlin/JVM and Kotlin/JS by building a client-server application that makes use of shared code, serialization, and other
multiplatform paradigms. It also provides a brief introduction to working with Ktor both as a server- and client-side
framework.
Sample
projects
Kotlin Multiplatform Mobile (KMM) samples
KotlinConf app
Kotlin
Multiplatform
Mobile
59
Multiplatform Mobile projects are in Alpha. Language features and tooling may change in future Kotlin versions.
Kotlin Multiplatform Mobile (KMM) is an SDK designed to simplify creating cross-platform mobile applications. With the
help of KMM, you can share common code between iOS and Android apps and write platform-specific code only where
it’s necessary. For example, to implement a native UI or when working with platform-specific APIs.
Get
started
with
Kotlin
Multiplatform
Mobile
Get started with KMM if you're already familiar with the Kotlin language and want to try out Kotlin Multiplatform Mobile
(KMM). If you're new to Kotlin, get started with these tutorials.
If you want to introduce KMM to your team, look through our recommendations.
Supported
platforms
KMM supports the following mobile targets:
Apple iOS on ARM64 (iPhone 5s and newer), ARM32 (earlier models) platforms, and desktop simulators on both Intel-
based and Apple Silicon platforms
Apple watchOS on ARM64 (Apple Watch Series 4 and newer), ARM32 (earlier models) platforms, and desktop
simulators on both Intel-based and Apple Silicon platforms
KMM is built on top of the Kotlin Multiplatform technology, which supports other platforms inlcuding JavaScript, Linux,
WebAssembly, and more.
Sample
projects
Check our list of KMM sample projects for inspiration.
Videos
Learn KMM with Kotlin Multiplatform Multiverse videos on YouTube.
Community
60
Kotlin Slack: Get an invite and join the #multiplatform channel.
Security
We do our best to make sure our software is free of security vulnerabilities. To reduce the risk of introducing a
vulnerability, you can follow Kotlin security recommendations.
We are very eager and grateful to hear about any security issues you find. To report vulnerabilities that you discover in any
part of KMM, please post a message directly to our issue tracker or send us an email.
For further information on how our responsible disclosure process works, please check the JetBrains Coordinated
Disclosure Policy.
Kotlin
for
server
side
Kotlin is a great fit for developing server-side applications, allowing you to write concise and expressive code while
maintaining full compatibility with existing Java-based technology stacks and a smooth learning curve:
Expressiveness: Kotlin's innovative language features, such as its support for type-safe builders and delegated
properties, help build powerful and easy-to-use abstractions.
Scalability: Kotlin's support for coroutines helps build server-side applications that scale to massive numbers of clients
with modest hardware requirements.
Interoperability: Kotlin is fully compatible with all Java-based frameworks, which lets you stay on your familiar
technology stack while reaping the benefits of a more modern language.
Migration: Kotlin supports gradual, step by step migration of large codebases from Java to Kotlin. You can start writing
new code in Kotlin while keeping older parts of your system in Java.
Tooling: In addition to great IDE support in general, Kotlin offers framework-specific tooling (for example, for Spring) in
the plugin for IntelliJ IDEA Ultimate.
Learning Curve: For a Java developer, getting started with Kotlin is very easy. The automated Java to Kotlin converter
included in the Kotlin plugin helps with the first steps. Kotlin Koans offer a guide through the key features of the
language with a series of interactive exercises.
Frameworks
for
server-side
development
with
Kotlin
Spring makes use of Kotlin's language features to offer more concise APIs, starting with version 5.0. The online project
generator allows you to quickly generate a new project in Kotlin.
61
Vert.x, a framework for building reactive Web applications on the JVM, offers dedicated support for Kotlin, including
full documentation.
Ktor is a framework built by JetBrains for creating Web applications in Kotlin, making use of coroutines for high
scalability and offering an easy-to-use and idiomatic API.
kotlinx.html is a DSL that can be used to build HTML in a Web application. It serves as an alternative to traditional
templating systems such as JSP and FreeMarker.
Micronaut is a modern, JVM-based, full-stack framework for building modular, easily testable microservice and
serverless applications. It comes with a lot of built-in, handy features.
http4k is the functional toolkit with a tiny footprint for Kotlin HTTP applications, written in pure Kotlin. The library is
based on the "Your Server as a Function" paper from Twitter and represents modeling both HTTP Servers and Clients
as simple Kotlin functions that can be composed together.
Javalin is a very lightweight web framework for Kotlin and Java which supports WebSockets, HTTP2 and async
requests.
The available options for persistence include direct JDBC access, JPA, as well as using NoSQL databases through
their Java drivers. For JPA, the kotlin-jpa compiler plugin adapts Kotlin-compiled classes to the requirements of the
framework.
Deploying
Kotlin
server-side
applications
Kotlin applications can be deployed into any host that supports Java Web applications, including Amazon Web Services,
Google Cloud Platform and more.
To deploy Kotlin applications on Heroku, you can follow the official Heroku tutorial.
AWS Labs provides a sample project showing the use of Kotlin for writing AWS Lambda functions.
Google Cloud Platform offers a series of tutorials for deploying Kotlin applications to GCP, both for Ktor and App Engine
and Spring and App engine. In addition there is an interactive code lab for deploying a Kotlin Spring application.
Users
of
Kotlin
on
the
server
side
Corda is an open-source distributed ledger platform, supported by major banks, and built entirely in Kotlin.
JetBrains Account, the system responsible for the entire license sales and validation process at JetBrains, is written in
100% Kotlin and has been running in production since 2015 with no major issues.
Next
steps
For a more in-depth introduction to the language, check out the Kotlin documentation on this site and Kotlin Koans.
62
Micronaut also has a lot of well-detailed guides, showing how you can build microservices in Kotlin.
http4k provides the CLI to generate fully formed projects, and a starter repo to generate an entire CD pipeline using
GitHub, Travis, and Heroku with a single bash command.
Want to migrate from Java to Kotlin? Learn how to perform typical tasks with strings in Java and Kotlin.
Kotlin
for
Android
Android mobile development has been Kotlin-first since Google I/O in 2019.
Less code combined with greater readability. Spend less time writing your code and working to understand the code
of others.
Mature language and environment. Since its creation in 2011, Kotlin has developed continuously, not only as a
language but as a whole ecosystem with robust tooling. Now it's seamlessly integrated in Android Studio and is
actively used by many companies for developing Android applications.
Kotlin support in Android Jetpack and other libraries. KTX extensions add Kotlin language features, such as
coroutines, extension functions, lambdas, and named parameters, to existing Android libraries.
Interoperability with Java. You can use Kotlin along with the Java programming language in your applications without
needing to migrate all your code to Kotlin.
Support for multiplatform development. You can use Kotlin for developing not only Android but also iOS, backend, and
web applications. Enjoy the benefits of sharing the common code among the platforms.
Code safety. Less code and better readability lead to fewer errors. The Kotlin compiler detects these remaining errors,
making the code safe.
Easy learning. Kotlin is very easy to learn, especially for Java developers.
Big community. Kotlin has great support and many contributions from the community, which is growing all over the
world. According to Google, over 60% of the top 1000 apps on the Play Store use Kotlin.
Many startups and Fortune 500 companies have already developed Android applications using Kotlin – see the list at
the Google website for Kotlin developers.
If you want to start using Kotlin for Android development, read Google’s recommendation for getting started with
Kotlin on Android.
If you're new to Android and want to learn to create applications with Kotlin, check out this Udacity course.
Kotlin
for
JavaScript
Kotlin/JS provides the ability to transpile your Kotlin code, the Kotlin standard library, and any compatible dependencies
63
to JavaScript. The current implementation of Kotlin/JS targets ES5.
The recommended way to use Kotlin/JS is via the kotlin.js and kotlin.multiplatform Gradle plugins. They provide a central
and convenient way to set up and control Kotlin projects targeting JavaScript. This includes essential functionality such as
controlling the bundling of your application, adding JavaScript dependencies directly from npm, and more. To get an
overview of the available options, check out the Kotlin/JS project setup documentation.
Use
cases
for
Kotlin/JS
There are numerous ways that Kotlin/JS can be used. To provide you some inspiration, here's a non-exhaustive list of
scenarios in which you can use Kotlin/JS.
Kotlin/JS allows you to leverage powerful browser and web APIs in a type-safe fashion. Create, modify and interact
with elements in the Document Object Model (DOM), use Kotlin code to control the rendering of canvas or WebGL
components, and enjoy access to many more of the features supported in modern browsers.
Write full, type-safe React applications with Kotlin/JS using the kotlin-wrappers provided by JetBrains, which
provide convenient abstractions and deep integrations for one of the most popular JavaScript frameworks. kotlin-
wrappers also provides support for a select number of adjacent technologies like react-redux, react-router, or
styled-components. Interoperability with the JavaScript ecosystem also means that you can also use third-party
React components and component libraries.
Use the Kotlin/JS frameworks that take full advantage of Kotlin concepts, its expressive power and conciseness.
The Node.js target provided by Kotlin/JS enables you to create applications that run on a server or get executed on
serverless infrastructure. You benefit from the same advantages as other applications executing in a JavaScript
runtime, such as faster startup speed and a reduced memory footprint. With kotlinx-nodejs, you have typesafe
access to the Node.js API directly from your Kotlin code.
Use Kotlin's multiplatform projects to share code with other Kotlin targets
All Kotlin/JS functionality can also be accessed when using the Kotlin multiplatform Gradle plugin.
If you have a backend written in Kotlin, you can share common code such as data models or validation logic with a
frontend written in Kotlin/JS, allowing you to write and maintain full-stack web applications.
You could also share business logic between your web interface and mobile apps for Android and iOS, and avoid
duplicating commonly used functionality like providing abstractions around REST API endpoints, user
authentication, or your domain models.
You don't have to write your whole application in Kotlin/JS, either – you can also generate libraries from your
Kotlin code that can be consumed as modules from any code base written in JavaScript or TypeScript, regardless
of other frameworks or technologies used. This approach of creating hybrid applications allows you to leverage the
64
competencies that you and your team might already have around web development, while helping you reduce the
amount of duplicated work, and making it easier to keep your web target consistent with other targets of your
application.
Of course, this is not a complete list of how you can use Kotlin/JS to your advantage, but merely a selection of cherry-
picked cases. We invite you to experiment with combinations of these use cases, and find out what works best for your
project.
Regardless of your specific use case, Kotlin/JS projects can use compatible libraries from the Kotlin ecosystem, as well
as third-party libraries from the JavaScript and TypeScript ecosystems. To use the latter from Kotlin code, you can either
provide your own typesafe wrappers, use community-maintained wrappers, or let Dukat automatically generate Kotlin
declarations for you. Using the Kotlin/JS-exclusive dynamic type allows you to loosen the constraints of Kotlin's type
system, allowing you to skip creating detailed library wrappers - at the expense of type safety.
Kotlin/JS is also compatible with the most common module systems: UMD, CommonJS, and AMD. Being able to produce
and consume modules means that you can interact with the JavaScript ecosystem in a structured manner.
Kotlin/JS
frameworks
Modern web development benefits significantly from frameworks that simplify building web applications. Here are
examples of popular web frameworks for Kotlin/JS written by different authors:
KVision
KVision is an object-oriented web framework that makes it possible to write applications in Kotlin/JS with ready-to-use
components that can be used as building blocks for your application’s user interface. You can use both reactive and
imperative programming models to build your frontend, use connectors for Ktor, Spring Boot, and other frameworks to
integrate it with your server-side applications, and share code using Kotlin Multiplatform.
For updates and discussions about the framework, join #kvision and #javascript channels in the Kotlin Slack.
fritz2
fritz2 is a standalone framework for building reactive web user interfaces. It provides its own type-safe DSL for building
and rendering HTML elements, and it makes use of Kotlin’s coroutines and flows to express components and their
data bindings. It provides state management, validation, routing, and more out of the box, and integrates with Kotlin
Multiplatform projects.
For updates and discussions about the framework, join the #fritz2 and #javascript channels in the Kotlin Slack.
Doodle
Doodle is a vector-based UI framework for Kotlin/JS. Doodle applications use the browser’s graphics capabilities to
65
draw user interfaces instead of relying on DOM, CSS, or Javascript. By using this approach, Doodle gives you precise
control over the rendering of arbitrary UI elements, vector shapes, gradients, and custom visualizations.
For updates and discussions about the framework, join #doodle and #javascript channels in the Kotlin Slack.
Compose
for
Web
Compose for Web, a part of Compose Multiplatform brings Google's Jetpack Compose UI toolkit to your browser. It
allows you to build reactive web user interfaces using the concepts introduced by Jetpack Compose. It provides a DOM
API to describe your website, as well as an experimental set of multiplatform layout primitives. Compose for Web also
gives you the option to share parts of your UI code and logic across Android, desktop, and web.
Compose for Web is in Alpha, which means it hasn't reached the final shape yet, but you can already implement a proof-
of-concept for your production applications.
You can find more information about Compose Multiplatform on its landing page.
Join the #compose-web channel on Kotlin Slack to discuss Compose for Web, or #compose for general Compose
Multiplatform discussions.
Kotlin/JS,
Today
and
Tomorrow
Want to know more about Kotlin/JS?
In this video, Kotlin Developer Advocate Sebastian Aigner will explain the main Kotlin/JS benefits to you, share some tips
and use cases, and also tell you about the plans and upcoming features for Kotlin/JS.
Gif
66
Get
started
with
Kotlin/JS
If you're new to Kotlin, a good first step would be to familiarize yourself with the basic syntax of the language.
To start using Kotlin for JavaScript, please refer to the Set up a Kotlin/JS project, or pick a hands-on lab from the next
section to work through.
Hands-on
labs
for
Kotlin/JS
Hands-on labs are long-form tutorials that help you get to know a technology by guiding you through a self-contained
project related to a specific topic.
They include sample projects, which can serve as jumping-off points for your own projects, and contain useful snippets
and patterns.
Building Web Applications with React and Kotlin/JS guides you through the process of building a simple web
application using the React framework, shows how a typesafe Kotlin DSL for HTML makes it convenient to build
reactive DOM elements, and illustrates how to use third-party React components, and how to obtain information from
APIs, while writing the whole application logic in pure Kotlin/JS.
Building a Full Stack Web App with Kotlin Multiplatform teaches the concepts behind building an application that
targets Kotlin/JVM and Kotlin/JS by building a client-server application that makes use of common code, serialization,
and other multiplatform paradigms. It also provides a brief introduction into working with Ktor both as a server- and
client-side framework.
New
Kotlin/JS
IR
compiler
The new Kotlin/JS IR compiler (currently with Beta stability) comes with a number of improvements over the current
default compiler. For example, it improves the size of generated executables via dead code elimination and makes it
smoother to interoperate with the JavaScript ecosystem and its tooling. By generating TypeScript declaration files (d.ts)
from Kotlin code, the new compiler makes it easier to create “hybrid†applications that mix TypeScript and Kotlin
code, and leverage code-sharing functionality using Kotlin Multiplatform.
To learn more about the available features in the new Kotlin/JS IR compiler and how to try it for your project, visit the
Kotlin/JS IR compiler documentation page and the migration guide.
Join
the
Kotlin/JS
community
You can also join #javascript channel in the official Kotlin Slack and chat with the community and the team.
Kotlin
Native
67
Kotlin/Native is a technology for compiling Kotlin code to native binaries, which can run without a virtual machine. It is an
LLVM based backend for the Kotlin compiler and native implementation of the Kotlin standard library.
Why
Kotlin/Native?
Kotlin/Native is primarily designed to allow compilation for platforms where virtual machines are not desirable or possible,
for example, embedded devices or iOS. It solves the situations when a developer needs to produce a self-contained
program that does not require an additional runtime or virtual machine.
Target
platforms
Kotlin/Native supports the following platforms:
macOS
Linux
Windows (MinGW)
Android NDK
Interoperability
Kotlin/Native supports two-way interoperability with the Native world. On the one hand, the compiler creates:
On the other hand, Kotlin/Native supports interoperability to use existing libraries directly from Kotlin/Native:
It is easy to include a compiled Kotlin code into existing projects written in C, C++, Swift, Objective-C, and other
languages. It is also easy to use existing native code, static or dynamic C libraries, Swift/Objective-C frameworks,
graphical engines, and anything else directly from Kotlin/Native.
Kotlin/Native libraries help to share Kotlin code between projects. POSIX, gzip, OpenGL, Metal, Foundation, and many
other popular libraries and Apple frameworks are pre-imported and included as Kotlin/Native libraries into the compiler
68
package.
Sharing
code
between
platforms
Multiplatform projects allow sharing common Kotlin code between multiple platforms, including Android, iOS, JVM,
JavaScript, and native. Multiplatform libraries provide required APIs for the common Kotlin code and help develop shared
parts of a project in Kotlin code in one place and share it with all or several target platforms.
You can use Kotlin Multiplatform Mobile (KMM) to create multiplatform mobile applications with code shared between
Android and iOS.
How
to
start
Tutorials
and
documentation
New to Kotlin? Take a look at Getting started with Kotlin.
Recommended documentation:
Multiplatform documentation
C interop
Swift/Objective-C interop
Recommended tutorials:
Sample
projects
Kotlin Multiplatform Mobile samples
KotlinConf app
69
KotlinConf Spinner app
Kotlin
for
data
science
From building data pipelines to productionizing machine learning models, Kotlin can be a great choice for working with
data:
Static typing and null safety help create reliable, maintainable code that is easy to troubleshoot.
Being a JVM language, Kotlin gives you great performance and an ability to leverage an entire ecosystem of tried and
true Java libraries.
Interactive
editors
Notebooks such as Jupyter Notebook and Apache Zeppelin provide convenient tools for data visualization and
exploratory research. Kotlin integrates with these tools to help you explore data, share your findings with colleagues, or
build up your data science and machine learning skills.
Jupyter
Kotlin
kernel
The Jupyter Notebook is an open-source web application that allows you to create and share documents (aka
"notebooks") that can contain code, visualizations, and markdown text. Kotlin-jupyter is an open source project that
brings Kotlin support to Jupyter Notebook.
70
Kotlin in Jupyter notebook
Check out Kotlin kernel's GitHub repo for installation instructions, documentation, and examples.
Zeppelin
Kotlin
interpreter
Apache Zeppelin is a popular web-based solution for interactive data analytics. It provides strong support for the Apache
Spark cluster computing system, which is particularly useful for data engineering. Starting from version 0.9.0, Apache
Zeppelin comes with bundled Kotlin interpreter.
71
Kotlin in Zeppelin notebook
Libraries
The ecosystem of libraries for data-related tasks created by the Kotlin community is rapidly expanding. Here are some
libraries that you may find useful:
Kotlin
libraries
Multik: multidimensional arrays in Kotlin. The library provides Kotlin-idiomatic, type- and dimension-safe API for
mathematical operations over multidimensional arrays. Multik offers swappable JVM and native computational
engines, and a combination of the two for optimal performance.
KotlinDL is a high-level Deep Learning API written in Kotlin and inspired by Keras. It offers simple APIs for training
deep learning models from scratch, importing existing Keras models for inference, and leveraging transfer learning for
tweaking existing pre-trained models to your tasks.
Kotlin for Apache Spark adds a missing layer of compatibility between Kotlin and Apache Spark. It allows Kotlin
developers to use familiar language features such as data classes, and lambda expressions as simple expressions in
curly braces or method references.
kotlin-statistics is a library providing extension functions for exploratory and production statistics. It supports basic
numeric list/sequence/array functions (from sum to skewness), slicing operators (such as countBy,
simpleRegressionBy), binning operations, discrete PDF sampling, naive bayes classifier, clustering, linear regression,
and much more.
kmath is a library inspired by NumPy. This library supports algebraic structures and operations, array-like structures,
math expressions, histograms, streaming operations, a wrapper around commons-math and koma, and more.
krangl is a library inspired by R's dplyr and Python's pandas. This library provides functionality for data manipulation
using a functional-style API; it also includes functions for filtering, transforming, aggregating, and reshaping tabular
data.
lets-plot is a plotting library for statistical data written in Kotlin. Lets-Plot is multiplatform and can be used not only with
72
JVM, but also with JS and Python.
kravis is another library for the visualization of tabular data inspired by R's ggplot.
londogard-nlp-toolkit is a library that provides utilities when working with natural language processing such as
word/subword/sentence embeddings, word-frequencies, stopwords, stemming, and much more.
Java
libraries
Since Kotlin provides first-class interop with Java, you can also use Java libraries for data science in your Kotlin code.
Here are some examples of such libraries:
Smile- a comprehensive machine learning, natural language processing, linear algebra, graph, interpolation, and
visualization system. Besides Java API, Smile also provides a functional Kotlin API along with Scala and Clojure API.
Smile-NLP-kt- a Kotlin rewrite of the Scala implicits for the natural language processing part of Smile in the format
of extension functions and interfaces.
Apache Commons Math- a general math, statistics, and machine learning library for Java
If this list doesn’t cover your needs, you can find more options in the Kotlin Data Science Resources digest from
Thomas Nield.
Kotlin
for
competitive
programming
This tutorial is designed both for competitive programmers that did not use Kotlin before and for Kotlin developers that
did not participate in any competitive programming events before. It assumes the corresponding programming skills.
Competitive programming is a mind sport where contestants write programs to solve precisely specified algorithmic
problems within strict constraints. Problems can range from simple ones that can be solved by any software developer
and require little code to get a correct solution, to complex ones that require knowledge of special algorithms, data
73
structures, and a lot of practice. While not being specifically designed for competitive programming, Kotlin incidentally fits
well in this domain, reducing the typical amount of boilerplate that a programmer needs to write and read while working
with the code almost to the level offered by dynamically-typed scripting languages, while having tooling and performance
of a statically-typed language.
See Get started with Kotlin/JVM on how to set up development environment for Kotlin. In competitive programming, a
single project is usually created and each problem's solution is written in a single source file.
Simple
example:
Reachable
Numbers
problem
Let's take a look at a concrete example.
Codeforces Round 555 was held on April 26th for 3rd Division, which means it had problems fit for any developer to try.
You can use this link to read the problems. The simplest problem in the set is the Problem A: Reachable Numbers. It asks
to implement a straightforward algorithm described in the problem statement.
We'd start solving it by creating a Kotlin source file with an arbitrary name. A.kt will do well. First, we need to implement a
function specified in the problem statement as:
Let's denote a function f(x) in such a way: we add 1 to x, then, while there is at least one trailing zero in the resulting
number, we remove that zero.
Kotlin is a pragmatic and unopinionated language, supporting both imperative and function programming styles without
pushing the developer towards either one. We can implement the function f in functional style, using such Kotlin features
as tail recursion:
Alternatively, we can write an imperative implementation of the function f using the traditional while loop and mutable
variables that are denoted in Kotlin with var:
Types in Kotlin are optional in many places due to pervasive use of type-inference, but every declaration still has a well-
defined static type that is known at compilation.
Now, all is left is to write the main function that reads the input and implements the rest of the algorithm that the problem
statement asks for — to compute the number of different integers that are produced while repeatedly applying function f
to the initial number n that is given in the standard input.
By default, Kotlin runs on JVM and gives direct access to a rich and efficient collections library with general-purpose
74
collections and data-structures like dynamically-sized arrays (ArrayList), hash-based maps and sets (HashMap/ HashSet),
tree-based ordered maps and sets (TreeMap/ TreeSet), etc. Using a hash-set of integers to track values that were already
reached while applying function f, the straightforward imperative version of a solution to the problem can be written as
shown below:
fun main() {
var n = readLine()!!.toInt() // read integer from the input
val reached = HashSet<Int>() // a mutable hash set
while (reached.add(n)) n = f(n) // iterate function f
println(reached.size) // print answer to the output
}
Note the use of Kotlin's null-assertion operator !! after the readLine() function call. Kotlin's readLine() function is defined to
return a nullable type String? and returns null on the end of the input, which explicitly forces the developer to handle the
case of missing input.
There is no need to handle the case of misformatted input in competitive programming. In competitive programming, an
input format is always precisely specified and the actual input cannot deviate from the input specification in the problem
statement. That's what the null-assertion operator !! essentially does — it asserts that the input string is present and
throws an exception otherwise. Likewise, the String.toInt() function throws an exception if the input string is not an
integer.
All online competitive programming events allow the use of pre-written code, so you can define your own library of utility
functions that are geared towards competitive programming to make your actual solution code somewhat easier to read
and write. You would then use this code as a template for your solutions. For example, you can define the following helper
functions for reading inputs in competitive programming:
Note the use of private visibility modifier here. While the concept of visibility modifier is not relevant for competitive
programming at all, it allows you to place multiple solution files based on the same template without getting an error for
conflicting public declarations in the same package.
Functional
operators
example:
Long
Number
problem
For more complicated problems, Kotlin's extensive library of functional operations on collections comes in handy to
minimize the boilerplate and turn the code into a linear top-to-bottom and left-to-right fluent data transformation pipeline.
For example, the Problem B: Long Number problem takes a simple greedy algorithm to implement and it can be written
using this style without a single mutable variable:
fun main() {
// read input
val n = readLine()!!.toInt()
val s = readLine()!!
val fl = readLine()!!.split(" ").map { it.toInt() }
75
// define local function f
fun f(c: Char) = '0' + fl[c - '1']
// greedily find first and last indices
val i = s.indexOfFirst { c -> f(c) > c }
.takeIf { it >= 0 } ?: s.length
val j = s.withIndex().indexOfFirst { (j, c) -> j > i && f(c) < c }
.takeIf { it >= 0 } ?: s.length
// compose and write the answer
val ans =
s.substring(0, i) +
s.substring(i, j).map { c -> f(c) }.joinToString("") +
s.substring(j)
println(ans)
}
In this dense code, in addition to collection transformations, you can see such handy Kotlin features as local functions
and the elvis operator ?: that allow to express idioms like "take the value if it is positive or else use length" with a concise
and readable expressions like .takeIf { it >= 0 } ?: s.length, yet it is perfectly fine with Kotlin to create additional mutable
variables and express the same code in imperative style, too.
To make reading the input in competitive programming tasks like this more concise, you can have the following list of
helper input-reading functions:
With these helpers, the part of code for reading input becomes simpler, closely following the input specification in the
problem statement line by line:
// read input
val n = readInt()
val s = readLn()
val fl = readInts()
Note that in competitive programming it is customary to give variables shorter names than it is typical in industrial
programming practice, since the code is to be written just once and not supported thereafter. However, these names are
usually still mnemonic — a for arrays, i, j, etc for indices, r, and c for row and column numbers in tables, x and y for
coordinates, etc. It is easier to keep the same names for input data as it is given in the problem statement. However, more
complex problems require more code which leads to using longer self-explanatory variable and function names.
More
tips
and
tricks
Competitive programming problems often have input like this:
In Kotlin this line can be concisely parsed with the following statement using destructuring declaration from a list of
integers:
76
val (n, k) = readInts()
It might be temping to use JVM's java.util.Scanner class to parse less structured input formats. Kotlin is designed to
interoperate well with JVM libraries, so that their use feels quite natural in Kotlin. However, beware that java.util.Scanner is
extremely slow. So slow, in fact, that parsing 10 5 or more integers with it might not fit into a typical 2 second time-limit,
which a simple Kotlin's split(" ").map { it.toInt() } would handle.
Writing output in Kotlin is usually straightforward with println(...) calls and using Kotlin's string templates. However, care
must be taken when output contains on order of 10 5 lines or more. Issuing so many println calls is too slow, since the
output in Kotlin is automatically flushed after each line. A faster way to write many lines from an array or a list is using
joinToString() function with "\n" as the separator, like this:
Learning
Kotlin
Kotlin is easy to learn, especially for those who already know Java. A short introduction to the basic syntax of Kotlin for
software developers can be found directly in the reference section of the web site starting from basic syntax.
IDEA has built-in Java-to-Kotlin converter. It can be used by people familiar with Java to learn the corresponding Kotlin
syntactic constructions, but it is not perfect and it is still worth familiarizing yourself with Kotlin and learning the Kotlin
idioms.
A great resource to study Kotlin syntax and API of the Kotlin standard library are Kotlin Koans.
What's
new
in
Kotlin
1.5.30
Release date: 24 August 2021
Kotlin 1.5.30 offers language updates including previews of future changes, various improvements in platform support
and tooling, and new standard library functions.
Language features, including experimental sealed when statements, changes in using opt-in requirement, and others
You can also find a short overview of the changes in the release blog post and this video:
77
Gif
Language
features
Kotlin 1.5.30 is presenting previews of future language changes and bringing improvements to the opt-in requirement
mechanism and type inference:
Exhaustive
when
statements
for
sealed
and
Boolean
subjects
Support for sealed (exhaustive) when statements is Experimental. It may be dropped or changed at any time.
Opt-in is required (see the details below), and you should use it only for evaluation purposes. We would
appreciate your feedback on it in YouTrack.
An exhaustive when statement contains branches for all possible types or values of its subject or for some types plus an
else branch. In other words, it covers all possible cases.
78
We’re planning to prohibit non-exhaustive when statements soon to make the behavior consistent with when
expressions. To ensure smooth migration, you can configure the compiler to report warnings about non-exhaustive when
statements with a sealed class or a Boolean. Such warnings will appear by default in Kotlin 1.6 and will become errors
later.
fun main() {
val x: Mode = Mode.ON
when (x) {
Mode.ON -> println("ON")
}
// WARNING: Non exhaustive 'when' statements on sealed classes/interfaces
// will be prohibited in 1.7, add an 'OFF' or 'else' branch instead
To enable this feature in Kotlin 1.5.30, use language version 1.6. You can also change the warnings to errors by enabling
progressive mode.
Kotlin
kotlin {
sourceSets.all {
languageSettings.apply {
languageVersion = "1.6"
//progressiveMode = true // false by default
}
}
}
Groovy
kotlin {
sourceSets.all {
languageSettings {
languageVersion = '1.6'
//progressiveMode = true // false by default
}
79
}
}
Suspending
functions
as
supertypes
Support for suspending functions as supertypes is Experimental. It may be dropped or changed at any time.
Opt-in is required (see the details below), and you should use it only for evaluation purposes. We would
appreciate your feedback on it in YouTrack.
Kotlin 1.5.30 provides a preview of the ability to use a suspend functional type as a supertype with some limitations.
Kotlin
kotlin {
sourceSets.all {
languageSettings.apply {
languageVersion = "1.6"
}
}
}
Groovy
kotlin {
sourceSets.all {
languageSettings {
languageVersion = '1.6'
}
}
}
You can’t mix an ordinary functional type and a suspend functional type as supertype. This is because of the
implementation details of suspend functional types in the JVM backend. They are represented in it as ordinary
functional types with a marker interface. Because of the marker interface, there is no way to tell which of the
superinterfaces are suspended and which are ordinary.
You can't use multiple suspend functional supertypes. If there are type checks, you also can’t use multiple
80
ordinary functional supertypes.
Requiring
opt-in
on
implicit
usages
of
experimental
APIs
The opt-in requirement mechanism is Experimental. It may change at any time. See how to opt-in. Use it only
for evaluation purposes. We would appreciate your feedback on it in YouTrack.
The author of a library can mark an experimental API as requiring opt-in to inform users about its experimental state. The
compiler raises a warning or error when the API is used and requires explicit consent to suppress it.
In Kotlin 1.5.30, the compiler treats any declaration that has an experimental type in the signature as experimental.
Namely, it requires opt-in even for implicit usages of an experimental API. For example, if the function’s return type is
marked as an experimental API element, a usage of the function requires you to opt-in even if the declaration is not
marked as requiring an opt-in explicitly.
// Library code
@MyDateTime
class DateProvider // A class requiring opt-in
// Client code
Changes
to
using
opt-in
requirement
annotations
with
different
targets
The opt-in requirement mechanism is Experimental. It may change at any time. See how to opt-in. Use it only
for evaluation purposes. We would appreciate your feedback on it in YouTrack.
Kotlin 1.5.30 presents new rules for using and declaring opt-in requirement annotations on different targets. The compiler
now reports an error for use cases that are impractical to handle at compile time. In Kotlin 1.5.30:
81
Marking local variables and value parameters with opt-in requirement annotations is forbidden at the use site.
Marking backing fields and getters is forbidden. You can mark the basic property instead.
Setting TYPE and TYPE_PARAMETER annotation targets is forbidden at the opt-in requirement annotation declaration
site.
Improvements
to
type
inference
for
recursive
generic
types
In Kotlin and Java, you can define a recursive generic type, which references itself in its type parameters. In Kotlin 1.5.30,
the Kotlin compiler can infer a type argument based only on upper bounds of the corresponding type parameter if it is a
recursive generic. This makes it possible to create various patterns with recursive generic types that are often used in
Java to make builder APIs.
// Kotlin 1.5.20
val containerA = PostgreSQLContainer<Nothing>(DockerImageName.parse("postgres:13-alpine")).apply
{
withDatabaseName("db")
withUsername("user")
withPassword("password")
withInitScript("sql/schema.sql")
}
// Kotlin 1.5.30
val containerB = PostgreSQLContainer(DockerImageName.parse("postgres:13-alpine"))
.withDatabaseName("db")
.withUsername("user")
.withPassword("password")
.withInitScript("sql/schema.sql")
You can enable the improvements by passing the -Xself-upper-bound-inference or the -language-version 1.6 compiler
options. See other examples of newly supported use cases in this YouTrack ticket.
Eliminating
builder
inference
restrictions
Builder inference is a special kind of type inference that allows you to infer the type arguments of a call based on type
information from other calls inside its lambda argument. This can be useful when calling generic builder functions such as
buildList() or sequence(): buildList { add("string") }.
Inside such a lambda argument, there was previously a limitation on using the type information that the builder inference
tries to infer. This means you can only specify it and cannot get it. For example, you cannot call get() inside a lambda
argument of buildList() without explicitly specified type arguments.
Kotlin 1.5.30 removes these limitations with the -Xunrestricted-builder-inference compiler option. Add this option to
enable previously prohibited calls inside a lambda argument of generic builder functions:
82
@kotlin.ExperimentalStdlibApi
val list = buildList {
add("a")
add("b")
set(1, null)
val x = get(1)
if (x != null) {
removeAt(1)
}
}
@kotlin.ExperimentalStdlibApi
val map = buildMap {
put("a", 1)
put("b", 1.1)
put("c", 2f)
}
Also, you can enable this feature with the -language-version 1.6 compiler option.
Kotlin/JVM
With Kotlin 1.5.30, Kotlin/JVM receives the following features:
See the Gradle section for Kotlin Gradle plugin updates on the JVM platform.
Instantiation
of
annotation
classes
Instantiation of annotation classes is Experimental. It may be dropped or changed at any time. Opt-in is
required (see the details below), and you should use it only for evaluation purposes. We would appreciate your
feedback on it in YouTrack.
With Kotlin 1.5.30 you can now call constructors of annotation classes in arbitrary code to obtain a resulting instance. This
feature covers the same use cases as the Java convention that allows the implementation of an annotation interface.
83
}
Use the -language-version 1.6 compiler option to enable this feature. Note that all current annotation class limitations,
such as restrictions to define non- val parameters or members different from secondary constructors, remain intact.
Improved
nullability
annotation
support
configuration
The Kotlin compiler can read various types of nullability annotations to get nullability information from Java. This
information allows it to report nullability mismatches in Kotlin when calling Java code.
In Kotlin 1.5.30, you can specify whether the compiler reports a nullability mismatch based on the information from
specific types of nullability annotations. Just use the compiler option -Xnullability-annotations=@<package-name>:
<report-level>. In the argument, specify the fully qualified nullability annotations package and one of these report levels:
See the full list of supported nullability annotations along with their fully qualified package names.
Here is an example showing how to enable error reporting for the newly supported RxJava 3 nullability annotations: -
Xnullability-annotations=@io.reactivex.rxjava3.annotations:strict. Note that all such nullability mismatches are warnings by
default.
Kotlin/Native
Kotlin/Native has received various changes and improvements:
Deprecation of linkage against DLLs without import libraries for MinGW targets
Apple
silicon
support
Kotlin 1.5.30 introduces native support for Apple silicon.
Previously, the Kotlin/Native compiler and tooling required the Rosetta translation environment for working on Apple
silicon hosts. In Kotlin 1.5.30, the translation environment is no longer needed – the compiler and tooling can run on
Apple silicon hardware without requiring any additional actions.
84
We’ve also introduced new targets that make Kotlin code run natively on Apple silicon:
macosArm64
iosSimulatorArm64
watchosSimulatorArm64
tvosSimulatorArm64
They are available on both Intel-based and Apple silicon hosts. All existing targets are available on Apple silicon hosts as
well.
Note that in 1.5.30 we provide only basic support for Apple silicon targets in the kotlin-multiplatform Gradle plugin.
Particularly, the new simulator targets aren’t included in the ios, tvos, and watchos target shortcuts. Learn how to use
Apple silicon targets with the target shortcuts. We will keep working to improve the user experience with the new targets.
Improved
Kotlin
DSL
for
the
CocoaPods
Gradle
plugin
To use the new DSL, update your project to Kotlin 1.5.30, and specify the parameters in the cocoapods section of your
build.gradle(.kts) file:
cocoapods {
frameworkName = "MyFramework" // This property is deprecated
// and will be removed in future versions
// New DSL for framework configuration:
framework {
// All Framework properties are supported
// Framework name configuration. Use this property instead of
// deprecated 'frameworkName'
baseName = "MyFramework"
// Dynamic framework support
isStatic = false
// Dependency export
export(project(":anotherKMMModule"))
transitiveExport = true
// Bitcode embedding
embedBitcode(BITCODE)
}
}
85
Support custom names for Xcode configuration
The Kotlin CocoaPods Gradle plugin supports custom names in the Xcode build configuration. It will also help you if
you’re using special names for the build configuration in Xcode, for example Staging.
To specify a custom name, use the xcodeConfigurationToNativeBuildType parameter in the cocoapods section of your
build.gradle(.kts) file:
cocoapods {
// Maps custom Xcode configuration to NativeBuildType
xcodeConfigurationToNativeBuildType["CUSTOM_DEBUG"] = NativeBuildType.DEBUG
xcodeConfigurationToNativeBuildType["CUSTOM_RELEASE"] = NativeBuildType.RELEASE
}
This parameter will not appear in the podspec file. When Xcode runs the Gradle build process, the Kotlin CocoaPods
Gradle plugin will select the necessary native build type.
There’s no need to declare the Debug and Release configurations because they are supported by default.
Experimental
interoperability
with
Swift
5.5
async/await
Concurrency interoperability with Swift async/await is Experimental. It may be dropped or changed at any time.
You should use it only for evaluation purposes. We would appreciate your feedback on it in YouTrack.
We added support for calling Kotlin’s suspending functions from Objective-C and Swift in 1.4.0, and now we’re
improving it to keep up with a new Swift 5.5 feature – concurrency with async and await modifiers.
The Kotlin/Native compiler now emits the _Nullable_result attribute in the generated Objective-C headers for suspending
functions with nullable return types. This makes it possible to call them from Swift as async functions with the proper
nullability.
Note that this feature is experimental and can be affected in the future by changes in both Kotlin and Swift. For now,
we’re offering a preview of this feature that has certain limitations, and we are eager to hear what you think. Learn
more about its current state and leave your feedback in this YouTrack issue.
Improved
Swift/Objective-C
mapping
for
objects
and
companion
objects
Getting objects and companion objects can now be done in a way that is more intuitive for native iOS developers. For
example, if you have the following objects in Kotlin:
object MyObject {
val x = "Some value"
}
class MyClass {
86
companion object {
val x = "Some value"
}
}
To access them in Swift, you can use the shared and companion properties:
MyObject.shared
MyObject.shared.x
MyClass.companion
MyClass.Companion.shared
Deprecation
of
linkage
against
DLLs
without
import
libraries
for
MinGW
targets
LLD is a linker from the LLVM project, which we plan to start using in Kotlin/Native for MinGW targets because of its
benefits over the default ld.bfd – primarily its better performance.
However, the latest stable version of LLD doesn’t support direct linkage against DLL for MinGW (Windows) targets.
Such linkage requires using import libraries. Although they aren’t needed with Kotlin/Native 1.5.30, we’re adding a
warning to inform you that such usage is incompatible with LLD that will become the default linker for MinGW in the
future.
Please share your thoughts and concerns about the transition to the LLD linker in this YouTrack issue.
Kotlin
Multiplatform
1.5.30 brings the following notable updates to Kotlin Multiplatform:
Ability
to
use
custom
cinterop
libraries
in
shared
native
code
Kotlin Multiplatform gives you an option to use platform-dependent interop libraries in shared source sets. Before 1.5.30,
this worked only with platform libraries shipped with Kotlin/Native distribution. Starting from 1.5.30, you can use it with
your custom cinterop libraries. To enable this feature, add the kotlin.mpp.enableCInteropCommonization=true property in
your gradle.properties:
kotlin.mpp.enableGranularSourceSetsMetadata=true
kotlin.native.enableDependencyPropagation=false
kotlin.mpp.enableCInteropCommonization=true
87
Support
for
XCFrameworks
All Kotlin Multiplatform projects can now have XCFrameworks as an output format. Apple introduced XCFrameworks as a
replacement for universal (fat) frameworks. With the help of XCFrameworks you:
Can gather logic for all the target platforms and architectures in a single bundle.
Don't need to remove all unnecessary architectures before publishing the application to the App Store.
XCFrameworks is useful if you want to use your KMM framework for devices and simulators on Apple M1.
Kotlin
import org.jetbrains.kotlin.gradle.plugin.mpp.apple.XCFramework
plugins {
kotlin("multiplatform")
}
kotlin {
val xcf = XCFramework()
ios {
binaries.framework {
baseName = "shared"
xcf.add(this)
}
}
watchos {
binaries.framework {
baseName = "shared"
xcf.add(this)
}
}
tvos {
binaries.framework {
baseName = "shared"
xcf.add(this)
}
}
}
Groovy
import org.jetbrains.kotlin.gradle.plugin.mpp.apple.XCFrameworkConfig
plugins {
id 'org.jetbrains.kotlin.multiplatform'
}
kotlin {
def xcf = XCFrameworkConfig(project)
ios {
88
binaries.framework {
baseName = "shared"
xcf.add(it)
}
}
watchos {
binaries.framework {
baseName = "shared"
xcf.add(it)
}
}
tvos {
binaries.framework {
baseName = "shared"
xcf.add(it)
}
}
}
When you declare XCFrameworks, these new Gradle tasks will be registered:
assembleXCFramework
assembleReleaseXCFramework
New
default
publishing
setup
for
Android
artifacts
Using the maven-publish Gradle plugin, you can publish your multiplatform library for the Android target by specifying
Android variant names in the build script. The Kotlin Gradle plugin will generate publications automatically.
Before 1.5.30, the generated publication metadata included the build type attributes for every published Android variant,
making it compatible only with the same build type used by the library consumer. Kotlin 1.5.30 introduces a new default
publishing setup:
If all Android variants that the project publishes have the same build type attribute, then the published variants won't
have the build type attribute and will be compatible with any build type.
If the published variants have different build type attributes, then only those with the release value will be published
without the build type attribute. This makes the release variants compatible with any build type on the consumer side,
while non-release variants will only be compatible with the matching consumer build types.
To opt-out and keep the build type attributes for all variants, you can set this Gradle property:
kotlin.android.buildTypeAttribute.keep=true.
Kotlin/JS
Two major improvements are coming to Kotlin/JS with 1.5.30:
89
JS IR compiler backend reaches Beta
JS
IR
compiler
backend
reaches
Beta
The IR-based compiler backend for Kotlin/JS, which was introduced in 1.4.0 in Alpha, has reached Beta.
Previously, we published the migration guide for the JS IR backend to help you migrate your projects to the new backend.
Now we would like to present the Kotlin/JS Inspection Pack IDE plugin, which displays the required changes directly in
IntelliJ IDEA.
Better
debugging
experience
for
applications
with
the
Kotlin/JS
IR
backend
Kotlin 1.5.30 brings JavaScript source map generation for the Kotlin/JS IR backend. This will improve the Kotlin/JS
debugging experience when the IR backend is enabled, with full debugging support that includes breakpoints, stepping,
and readable stack traces with proper source references.
Learn more about how to debug Kotlin/JS in the browser or IntelliJ IDEA Ultimate.
Gradle
As a part of our mission to improve the Kotlin Gradle plugin user experience, we’ve implemented the following
features:
Support for Java toolchains, which includes an ability to specify a JDK home with the UsesKotlinJavaToolchain
interface for older Gradle versions
Support
for
Java
toolchains
Gradle 6.7 introduced the "Java toolchains support" feature. Using this feature, you can:
Run compilations, tests, and executables using JDKs and JREs that are different from the Gradle ones.
With toolchains support, Gradle can autodetect local JDKs and install missing JDKs that Gradle requires for the build.
Now Gradle itself can run on any JDK and still reuse the build cache feature.
The Kotlin Gradle plugin supports Java toolchains for Kotlin/JVM compilation tasks. A Java toolchain:
The ability to set the jdkHome option directly has been deprecated.
90
Sets the kotlinOptions.jvmTarget to the toolchain's JDK version if the user didn’t set the jvmTarget option
explicitly. If the toolchain is not configured, the jvmTarget field uses the default value. Learn more about JVM target
compatibility.
Use the following code to set a toolchain. Replace the placeholder <MAJOR_JDK_VERSION> with the JDK version you
would like to use:
Kotlin
kotlin {
jvmToolchain {
(this as
JavaToolchainSpec).languageVersion.set(JavaLanguageVersion.of(<MAJOR_JDK_VERSION>)) // “8â€
}
}
Groovy
kotlin {
jvmToolchain {
languageVersion.set(JavaLanguageVersion.of(<MAJOR_JDK_VERSION>)) // “8â€
}
}
Note that setting a toolchain via the kotlin extension will update the toolchain for Java compile tasks as well.
You can set a toolchain via the java extension, and Kotlin compilation tasks will use it:
java {
toolchain {
languageVersion.set(JavaLanguageVersion.of(<MAJOR_JDK_VERSION>)) // “8â€
}
}
For information about setting any JDK version for KotlinCompile tasks, look through the docs about setting the JDK
version with the Task DSL.
For Gradle versions from 6.1 to 6.6, use the UsesKotlinJavaToolchain interface to set the JDK home.
Ability
to
specify
JDK
home
with
UsesKotlinJavaToolchain
interface
All Kotlin tasks that support setting the JDK via kotlinOptions now implement the UsesKotlinJavaToolchain interface. To
set the JDK home, put a path to your JDK and replace the <JDK_VERSION> placeholder:
Kotlin
91
project.tasks
.withType<UsesKotlinJavaToolchain>()
.configureEach {
it.kotlinJavaToolchain.jdk.use(
"/path/to/local/jdk",
JavaVersion.<LOCAL_JDK_VERSION>
)
}
Groovy
project.tasks
.withType(UsesKotlinJavaToolchain.class)
.configureEach {
it.kotlinJavaToolchain.jdk.use(
'/path/to/local/jdk',
JavaVersion.<LOCAL_JDK_VERSION>
)
}
Use the UsesKotlinJavaToolchain interface for Gradle versions from 6.1 to 6.6. Starting from Gradle 6.7, use the Java
toolchains instead.
When using this feature, note that kapt task workers will only use process isolation mode, and the kapt.workers.isolation
property will be ignored.
Easier
way
to
explicitly
specify
Kotlin
daemon
JVM
arguments
In Kotlin 1.5.30, there’s a new logic for the Kotlin daemon’s JVM arguments. Each of the options in the following
list overrides the ones that came before it:
If nothing is specified, the Kotlin daemon inherits arguments from the Gradle daemon (as before). For example, in the
gradle.properties file:
org.gradle.jvmargs=-Xmx1500m -Xms=500m
If the Gradle daemon’s JVM arguments have the kotlin.daemon.jvm.options system property, use it as before:
org.gradle.jvmargs=-Dkotlin.daemon.jvm.options=-Xmx1500m -Xms=500m
kotlin.daemon.jvmargs=-Xmx1500m -Xms=500m
92
Kotlin
kotlin {
kotlinDaemonJvmArgs = listOf("-Xmx486m", "-Xms256m", "-XX:+UseParallelGC")
}
Groovy
kotlin {
kotlinDaemonJvmArgs = ["-Xmx486m", "-Xms256m", "-XX:+UseParallelGC"]
}
Kotlin
tasks
.matching { it.name == "compileKotlin" && it is CompileUsingKotlinDaemon }
.configureEach {
(this as CompileUsingKotlinDaemon).kotlinDaemonJvmArguments.set(listOf("-Xmx486m", "-
Xms256m", "-XX:+UseParallelGC"))
}
Groovy
tasks
.matching {
it.name == "compileKotlin" && it instanceof CompileUsingKotlinDaemon
}
.configureEach {
kotlinDaemonJvmArguments.set(["-Xmx1g", "-Xms512m"])
}
In this case a new Kotlin daemon instance can start on task execution. Learn more about the Kotlin
daemon’s interactions with JVM arguments.
For more information about the Kotlin daemon, see the Kotlin daemon and using it with Gradle.
Standard
library
Kotlin 1.5.30 is bringing improvements to the standard library’s Duration and Regex APIs:
93
Parsing Duration from String
Changing
Duration.toString()
output
The Duration API is Experimental. It may be dropped or changed at any time. Use it only for evaluation
purposes. We would appreciate hearing your feedback on it in YouTrack.
Before Kotlin 1.5.30, the Duration.toString() function would return a string representation of its argument expressed in the
unit that yielded the most compact and readable number value. From now on, it will return a string value expressed as a
combination of numeric components, each in its own unit. Each component is a number followed by the unit’s
abbreviated name: d, h, m, s. For example:
The way negative durations are represented has also been changed. A negative duration is prefixed with a minus sign (-),
and if it consists of multiple components, it is surrounded with parentheses: -12m and -(1h 30m).
Note that small durations of less than one second are represented as a single number with one of the subsecond units.
For example, ms (milliseconds), us (microseconds), or ns (nanoseconds): 140.884ms, 500us, 24ns. Scientific notation is
no longer used to represent them.
If you want to express duration in a single unit, use the overloaded Duration.toString(unit, decimals) function.
94
We recommend using Duration.toIsoString() in certain cases, including serialization and interchange.
Duration.toIsoString() uses the stricter ISO-8601 format instead of Duration.toString().
Parsing
Duration
from
String
The Duration API is Experimental. It may be dropped or changed at any time. Use it only for evaluation
purposes. We would appreciate hearing your feedback on it in this issue.
toString(unit, decimals).
toIsoString().
parseOrNull() and parseIsoStringOrNull(), which behave like the functions above but return null instead of throwing
IllegalArgumentException on invalid duration formats.
import kotlin.time.Duration
import kotlin.time.ExperimentalTime
@ExperimentalTime
fun main() {
//sampleStart
val isoFormatString = "PT1H30M"
val defaultFormatString = "1h 30m"
val singleUnitFormatString = "1.5h"
val invalidFormatString = "1 hour 30 minutes"
println(Duration.parse(isoFormatString)) // "1h 30m"
println(Duration.parse(defaultFormatString)) // "1h 30m"
println(Duration.parse(singleUnitFormatString)) // "1h 30m"
//println(Duration.parse(invalidFormatString)) // throws exception
println(Duration.parseOrNull(invalidFormatString)) // "null"
//sampleEnd
}
import kotlin.time.Duration
import kotlin.time.ExperimentalTime
@ExperimentalTime
95
fun main() {
//sampleStart
val isoFormatString = "PT1H30M"
val defaultFormatString = "1h 30m"
println(Duration.parseIsoString(isoFormatString)) // "1h 30m"
//println(Duration.parseIsoString(defaultFormatString)) // throws exception
println(Duration.parseIsoStringOrNull(defaultFormatString)) // "null"
//sampleEnd
}
Matching
with
Regex
at
a
particular
position
Regex.matchAt() and Regex.matchesAt() functions are Experimental. They may be dropped or changed at any
time. Use them only for evaluation purposes. We would appreciate hearing your feedback on them in YouTrack.
The new Regex.matchAt() and Regex.matchesAt() functions provide a way to check whether a regex has an exact match
at a particular position in a String or CharSequence.
fun main(){
//sampleStart
val releaseText = "Kotlin 1.5.30 is released!"
// regular expression: one digit, dot, one digit, dot, one or more digits
val versionRegex = "\\d[.]\\d[.]\\d+".toRegex()
println(versionRegex.matchesAt(releaseText, 0)) // "false"
println(versionRegex.matchesAt(releaseText, 7)) // "true"
//sampleEnd
}
fun main(){
//sampleStart
val releaseText = "Kotlin 1.5.30 is released!"
val versionRegex = "\\d[.]\\d[.]\\d+".toRegex()
println(versionRegex.matchAt(releaseText, 0)) // "null"
println(versionRegex.matchAt(releaseText, 7)?.value) // "1.5.30"
//sampleEnd
}
Splitting
Regex
to
a
sequence
96
Regex.splitToSequence() and CharSequence.splitToSequence(Regex) functions are Experimental. They may be
dropped or changed at any time. Use them only for evaluation purposes. We would appreciate hearing your
feedback on them in YouTrack.
The new Regex.splitToSequence() function is a lazy counterpart of split(). It splits the string around matches of the given
regex, but it returns the result as a Sequence so that all operations on this result are executed lazily.
fun main(){
//sampleStart
val colorsText = "green, red , brown&blue, orange, pink&green"
val regex = "[,\\s]+".toRegex()
val mixedColor = regex.splitToSequence(colorsText)
.onEach { println(it) }
.firstOrNull { it.contains('&') }
println(mixedColor) // "brown&blue"
//sampleEnd
}
Serialization
1.3.0-RC
kotlinx.serialization 1.3.0-RC is here with new JSON serialization capabilities:
What's
new
in
Kotlin
1.5.20
Release date: 24 June 2021
Kotlin 1.5.20 has fixes for issues discovered in the new features of 1.5.0, and it also includes various tooling
improvements.
You can find an overview of the changes in the release blog post and this video:
97
Gif
Kotlin/JVM
Kotlin 1.5.20 is receiving the following updates on the JVM platform:
Support for calling Java’s Lombok-generated methods within modules that have Kotlin and Java code
String
concatenation
via
invokedynamic
Kotlin 1.5.20 compiles string concatenations into dynamic invocations (invokedynamic) on JVM 9+ targets, thereby
keeping up with modern Java versions. More precisely, it uses StringConcatFactory.makeConcatWithConstants() for
string concatenation.
To switch back to concatenation via StringBuilder.append() used in previous versions, add the compiler option -Xstring-
concat=inline.
Learn how to add compiler options in Gradle, Maven, and the command-line compiler.
Support
for
JSpecify
nullness
annotations
The Kotlin compiler can read various types of nullability annotations to pass nullability information from Java to Kotlin.
Version 1.5.20 introduces support for the JSpecify project, which includes the standard unified set of Java nullness
annotations.
With JSpecify, you can provide more detailed nullability information to help Kotlin keep null-safety interoperating with
98
Java. You can set default nullability for the declaration, package, or module scope, specify parametric nullability, and
more. You can find more details about this in the JSpecify user guide.
// JavaClass.java
import *;
@NullMarked
public class JavaClass {
public String notNullableString() { return ""; }
public @Nullable String nullableString() { return ""; }
}
// Test.kt
fun kotlinFun() = with(JavaClass()) {
notNullableString().length // OK
nullableString().length // Warning: receiver nullability mismatch
}
In 1.5.20, all nullability mismatches according to the JSpecify-provided nullability information are reported as warnings.
Use the -Xjspecify-annotations=strict and -Xtype-enhancement-improvements-strict-mode compiler options to enable
strict mode (with error reporting) when working with JSpecify. Please note that the JSpecify project is under active
development. Its API and implementation can change significantly at any time.
Support
for
calling
Java’s
Lombok-generated
methods
within
modules
that
have
Kotlin
and
Java
code
The Lombok compiler plugin is Experimental. It may be dropped or changed at any time. Use it only for
evaluation purposes. We would appreciate your feedback on it in YouTrack.
Kotlin 1.5.20 introduces an experimental Lombok compiler plugin. This plugin makes it possible to generate and use
Java’s Lombok declarations within modules that have Kotlin and Java code. Lombok annotations work only in Java
sources and are ignored if you use them in Kotlin code.
@Getter, @Setter
@Data
@With
@Value
99
We're continuing to work on this plugin. To find out the detailed current state, visit the Lombok compiler plugin's
README.
Currently, we don't have plans to support the @Builder annotation. However, we can consider this if you vote for @Builder
in YouTrack.
Kotlin/Native
Kotlin/Native 1.5.20 offers a preview of the new feature and the tooling improvements:
Opt-in
export
of
KDoc
comments
to
generated
Objective-C
headers
The ability to export KDoc comments to generated Objective-C headers is Experimental. It may be dropped or
changed at any time. Opt-in is required (see the details below), and you should use it only for evaluation
purposes. We would appreciate your feedback on it in YouTrack.
You can now set the Kotlin/Native compiler to export the documentation comments (KDoc) from Kotlin code to the
Objective-C frameworks generated from it, making them visible to the frameworks’ consumers.
/**
* Prints the sum of the arguments.
* Properly handles the case when the sum doesn't fit in 32-bit integer.
*/
fun printSum(a: Int, b: Int) = println(a.toLong() + b)
/**
* Prints the sum of the arguments.
* Properly handles the case when the sum doesn't fit in 32-bit integer.
*/
+ (void)printSumA:(int32_t)a b:(int32_t)b __attribute__((swift_name("printSum(a:b:)")));
To try out this ability to export KDoc comments to Objective-C headers, use the -Xexport-kdoc compiler option. Add the
100
following lines to build.gradle(.kts) of the Gradle projects you want to export comments from:
Kotlin
kotlin {
targets.withType<org.jetbrains.kotlin.gradle.plugin.mpp.KotlinNativeTarget> {
compilations.get("main").kotlinOptions.freeCompilerArgs += "-Xexport-kdoc"
}
}
Groovy
kotlin {
targets.withType(org.jetbrains.kotlin.gradle.plugin.mpp.KotlinNativeTarget) {
compilations.get("main").kotlinOptions.freeCompilerArgs += "-Xexport-kdoc"
}
}
We’d be very grateful if you would share your feedback with us using this YouTrack ticket.
Compiler
bug
fixes
The Kotlin/Native compiler has received multiple bug fixes in 1.5.20. You can find the complete list in the changelog.
There is an important bug fix that affects compatibility: in previous versions, string constants that contained incorrect UTF
surrogate pairs were losing their values during compilation. Now such values are preserved. Application developers can
safely update to 1.5.20 – nothing will break. However, libraries compiled with 1.5.20 are incompatible with earlier
compiler versions. See this YouTrack issue for details.
Improved
performance
of
Array.copyInto()
inside
one
array
We’ve improved the way Array.copyInto() works when its source and destination are the same array. Now such
operations finish up to 20 times faster (depending on the number of objects being copied) due to memory management
optimizations for this use case.
Kotlin/JS
With 1.5.20, we’re publishing a guide that will help you migrate your projects to the new IR-based backend for
Kotlin/JS.
Migration
guide
for
the
JS
IR
backend
The new migration guide for the JS IR backend identifies issues you may encounter during migration and provides
solutions for them. If you find any issues that aren’t covered in the guide, please report them to our issue tracker.
101
Gradle
Kotlin 1.5.20 introduces the following features that can improve the Gradle experience:
Caching
for
annotation
processors'
classloaders
in
kapt
Caching for annotation processors' classloaders in kapt is Experimental. It may be dropped or changed at any
time. Use it only for evaluation purposes. We would appreciate your feedback on it in YouTrack.
There is now a new experimental feature that makes it possible to cache the classloaders of annotation processors in
kapt. This feature can increase the speed of kapt for consecutive Gradle runs.
To enable this feature, use the following properties in your gradle.properties file:
Deprecation
of
the
kotlin.parallel.tasks.in.project
build
property
With this release, Kotlin parallel compilation is controlled by the Gradle parallel execution flag --parallel. Using this flag,
Gradle executes tasks concurrently, increasing the speed of compiling tasks and utilizing the resources more efficiently.
You no longer need to use the kotlin.parallel.tasks.in.project property. This property has been deprecated and will be
removed in the next major release.
Standard
library
Kotlin 1.5.20 changes the platform-specific implementations of several functions for working with characters and as a
result brings unification across platforms:
Support for all Unicode digits in Char.digitToInt() for Kotlin/Native and Kotlin/JS.
102
Support
for
all
Unicode
digits
in
Char.digitToInt()
in
Kotlin/Native
and
Kotlin/JS
Char.digitToInt() returns the numeric value of the decimal digit that the character represents. Before 1.5.20, the function
supported all Unicode digit characters only for Kotlin/JVM: implementations on the Native and JS platforms supported
only ASCII digits.
From now, both with Kotlin/Native and Kotlin/JS, you can call Char.digitToInt() on any Unicode digit character and get its
numeric representation.
fun main() {
//sampleStart
val ten = '\u0661'.digitToInt() + '\u0039'.digitToInt() // ARABIC-INDIC DIGIT ONE + DIGIT
NINE
println(ten)
//sampleEnd
}
Unification
of
Char.isLowerCase()/isUpperCase()
implementations
across
platforms
The functions Char.isUpperCase() and Char.isLowerCase() return a boolean value depending on the case of the character.
For Kotlin/JVM, the implementation checks both the General_Category and the Other_Uppercase/ Other_Lowercase
Unicode properties.
Prior to 1.5.20, implementations for other platforms worked differently and considered only the general category. In
1.5.20, implementations are unified across platforms and use both properties to determine the character case:
fun main() {
//sampleStart
val latinCapitalA = 'A' // has "Lu" general category
val circledLatinCapitalA = 'â’¶' // has "Other_Uppercase" property
println(latinCapitalA.isUpperCase() && circledLatinCapitalA.isUpperCase())
//sampleEnd
}
What's
new
in
Kotlin
1.5.0
Release date: 5 May 2021
Kotlin 1.5.0 introduces new language features, stable IR-based JVM compiler backend, performance improvements, and
evolutionary changes such as stabilizing experimental features and deprecating outdated ones.
You can also find an overview of the changes in the release blog post.
Language
features
Kotlin 1.5.0 brings stable versions of the new language features presented for preview in 1.4.30:
103
JVM records support
Inline classes
Detailed descriptions of these features are available in this blog post and the corresponding pages of Kotlin
documentation.
JVM
records
support
Java is evolving fast, and to make sure Kotlin remains interoperable with it, we’ve introduced support for one of its
latest features – record classes.
In Kotlin code, you can use Java record classes like you would use typical classes with properties.
To use a Kotlin class as a record in Java code, make it a data class and mark it with the @JvmRecord annotation.
@JvmRecord
data class User(val name: String, val age: Int)
Gif
Sealed
interfaces
Kotlin interfaces can now have the sealed modifier, which works on interfaces in the same way it works on classes: all
implementations of a sealed interface are known at compile time.
104
sealed interface Polygon
You can rely on that fact, for example, to write exhaustive when expressions.
Additionally, sealed interfaces enable more flexible restricted class hierarchies because a class can directly inherit more
than one sealed interface.
Gif
Package-wide
sealed
class
hierarchies
Sealed classes can now have subclasses in all files of the same compilation unit and the same package. Previously, all
subclasses had to appear in the same file.
Direct subclasses may be top-level or nested inside any number of other named classes, named interfaces, or named
objects.
105
The subclasses of a sealed class must have a name that is properly qualified – they cannot be local or anonymous
objects.
Inline
classes
Inline classes are a subset of value-based classes that only hold values. You can use them as wrappers for a value of a
certain type without the additional overhead that comes from using memory allocations.
Inline classes can be declared with the value modifier before the name of the class:
@JvmInline
value class Password(val s: String)
Gif
Kotlin/JVM
Kotlin/JVM has received a number of improvements, both internal and user-facing. Here are the most notable among
106
them:
Stable
JVM
IR
backend
The IR-based backend for the Kotlin/JVM compiler is now Stable and enabled by default.
Starting from Kotlin 1.4.0, early versions of the IR-based backend were available for preview, and it has now become the
default for language version 1.5. The old backend is still used by default for earlier language versions.
You can find more details about the benefits of the IR backend and its future development in this blog post.
If you need to use the old backend in Kotlin 1.5.0, you can add the following lines to the project’s configuration file:
In Gradle:
Kotlin
tasks.withType<org.jetbrains.kotlin.gradle.dsl.KotlinJvmCompile> {
kotlinOptions.useOldBackend = true
}
Groovy
tasks.withType(org.jetbrains.kotlin.gradle.dsl.KotlinJvmCompile) {
kotlinOptions.useOldBackend = true
}
In Maven:
<configuration>
<args>
<arg>-Xuse-old-backend</arg>
</args>
</configuration>
107
New
default
JVM
target:
1.8
The default target version for Kotlin/JVM compilations is now 1.8. The 1.6 target is deprecated.
If you need a build for JVM 1.6, you can still switch to this target. Learn how:
in Gradle
in Maven
SAM
adapters
via
invokedynamic
Kotlin 1.5.0 now uses dynamic invocations (invokedynamic) for compiling SAM (Single Abstract Method) conversions:
The new implementation uses LambdaMetafactory.metafactory() and auxiliary wrapper classes are no longer generated
during compilation. This decreases the size of the application’s JAR, which improves the JVM startup performance.
To roll back to the old implementation scheme based on anonymous class generation, add the compiler option -Xsam-
conversions=class.
Learn how to add compiler options in Gradle, Maven, and the command-line compiler.
Lambdas
via
invokedynamic
Compiling plain Kotlin lambdas into invokedynamic is Experimental. It may be dropped or changed at any time.
Opt-in is required (see details below), and you should use it only for evaluation purposes. We would appreciate
hearing your feedback on it in YouTrack.
Kotlin 1.5.0 is introducing experimental support for compiling plain Kotlin lambdas (which are not converted to an
instance of a functional interface) into dynamic invocations (invokedynamic). The implementation produces lighter
binaries by using LambdaMetafactory.metafactory(), which effectively generates the necessary classes at runtime.
Currently, it has three limitations compared to ordinary lambda compilation:
Experimental reflect API does not support lambdas created with LambdaMetafactory.
To try this feature, add the -Xlambdas=indy compiler option. We’d be grateful if you could share your feedback on it
using this YouTrack ticket.
Learn how to add compiler options in Gradle, Maven, and command-line compiler.
108
Deprecation
of
@JvmDefault
and
old
Xjvm-default
modes
Prior to Kotlin 1.4.0, there was the @JvmDefault annotation along with -Xjvm-default=enable and -Xjvm-
default=compatibility modes. They served to create the JVM default method for any particular non-abstract member in the
Kotlin interface.
In Kotlin 1.4.0, we introduced the new Xjvm-default modes, which switch on default method generation for the whole
project.
In Kotlin 1.5.0, we are deprecating @JvmDefault and the old Xjvm-default modes: -Xjvm-default=enable and -Xjvm-
default=compatibility.
Improvements
to
handling
nullability
annotations
Kotlin supports handling type nullability information from Java with nullability annotations. Kotlin 1.5.0 introduces a
number of improvements for the feature:
It reads nullability annotations on type arguments in compiled Java libraries that are used as dependencies.
Varargs
Fields
If a nullability annotation has multiple targets applicable to a type, and one of these targets is TYPE_USE, then
TYPE_USE is preferred. For example, the method signature @Nullable String[] f() becomes fun f(): Array<String?>! if
@Nullable supports both TYPE_USE and METHOD as targets.
For these newly supported cases, using the wrong type nullability when calling Java from Kotlin produces warnings. Use
the -Xtype-enhancement-improvements-strict-mode compiler option to enable strict mode for these cases (with error
reporting).
Kotlin/Native
Kotlin/Native is now more performant and stable. The notable changes are:
Performance improvements
109
Deactivation of the memory leak checker
Performance
improvements
In 1.5.0, Kotlin/Native is receiving a set of performance improvements that speed up both compilation and execution.
Compiler caches are now supported in debug mode for linuxX64 (only on Linux hosts) and iosArm64 targets. With
compiler caches enabled, most debug compilations complete much faster, except for the first one. Measurements
showed about a 200% speed increase on our test projects.
To use compiler caches for new targets, opt in by adding the following lines to the project’s gradle.properties:
If you encounter any issues after enabling the compiler caches, please report them to our issue tracker YouTrack.
Deactivation
of
the
memory
leak
checker
The built-in Kotlin/Native memory leak checker has been disabled by default.
It was initially designed for internal use, and it is able to find leaks only in a limited number of cases, not all of them.
Moreover, it later turned out to have issues that can cause application crashes. So we’ve decided to turn off the
memory leak checker.
The memory leak checker can still be useful for certain cases, for example, unit testing. For these cases, you can enable it
by adding the following line of code:
Platform.isMemoryLeakCheckerActive = true
Note that enabling the checker for the application runtime is not recommended.
Kotlin/JS
Kotlin/JS is receiving evolutionary changes in 1.5.0. We’re continuing our work on moving the JS IR compiler backend
towards stable and shipping other updates:
110
Upgrade
to
webpack
5
The Kotlin/JS Gradle plugin now uses webpack 5 for browser targets instead of webpack 4. This is a major webpack
upgrade that brings incompatible changes. If you’re using a custom webpack configuration, be sure to check the
webpack 5 release notes.
Frameworks
and
libraries
for
the
IR
compiler
The Kotlin/JS IR compiler is in Alpha. It may change incompatibly and require manual migration in the future.
We would appreciate your feedback on it in YouTrack.
Along with working on the IR-based backend for Kotlin/JS compiler, we encourage and help library authors to build their
projects in both mode. This means they are able to produce artifacts for both Kotlin/JS compilers, therefore growing the
ecosystem for the new compiler.
Many well-known frameworks and libraries are already available for the IR backend: KVision, fritz2, doodle, and others. If
you’re using them in your project, you can already build it with the IR backend and see the benefits it brings.
If you’re writing your own library, compile it in the 'both' mode so that your clients can also use it with the new
compiler.
Kotlin
Multiplatform
In Kotlin 1.5.0, choosing a testing dependency for each platform has been simplified and it is now done automatically by
the Gradle plugin.
A new API for getting a char category is now available in multiplatform projects.
Standard
library
The standard library has received a range of changes and improvements, from stabilizing experimental parts to adding
new features:
111
Duration API changes
New API for getting a char category now available in multiplatform code
You can learn more about the standard library changes in this blog post.
Gif
Stable
unsigned
integer
types
The UInt, ULong, UByte, UShort unsigned integer types are now Stable. The same goes for operations on these types,
ranges, and progressions of them. Unsigned arrays and operations on them remain in Beta.
Stable
locale-agnostic
API
for
upper/lowercasing
text
This release brings a new locale-agnostic API for uppercase/lowercase text conversion. It provides an alternative to the
toLowerCase(), toUpperCase(), capitalize(), and decapitalize() API functions, which are locale-sensitive. The new API helps
you avoid errors due to different locale settings.
Earlier
versions 1.5.0
alternative
112
Earlier
versions 1.5.0
alternative
String.toUpperCase() String.uppercase()
String.toLowerCase() String.lowercase()
Earlier
versions 1.5.0
alternative
Char.toUpperCase() Char.uppercaseChar():
Char
Char.uppercase(): String
For Kotlin/JVM, there are also overloaded uppercase(), lowercase(), and titlecase() functions with an explicit
Locale parameter.
The old API functions are marked as deprecated and will be removed in a future release.
See the full list of changes to the text processing functions in KEEP.
Stable
char-to-integer
conversion
API
Starting from Kotlin 1.5.0, new char-to-code and char-to-digit conversion functions are Stable. These functions replace
the current API functions, which were often confused with the similar string-to-Int conversion.
The new API removes this naming confusion, making the code behavior more transparent and unambiguous.
This release introduces Char conversions that are divided into the following sets of clearly named functions:
Functions to get the integer code of Char and to construct Char from the given code:
113
val Char.code: Int
An extension function for Int to convert the non-negative single digit it represents to the corresponding Char
representation:
The old conversion APIs, including Number.toChar() with its implementations (all except Int.toChar()) and Char extensions
for conversion to a numeric type, like Char.toInt(), are now deprecated.
Stable
Path
API
The experimental Path API with extensions for java.nio.file.Path is now Stable.
Floored
division
and
the
mod
operator
New operations for modular arithmetics have been added to the standard library:
floorDiv() returns the result of floored division. It is available for integer types.
mod() returns the remainder of floored division (modulus). It is available for all numeric types.
These operations look quite similar to the existing division of integers and rem() function (or the % operator), but they work
differently on negative numbers:
a.floorDiv(b) differs from a regular / in that floorDiv rounds the result down (towards the lesser integer), whereas /
truncates the result to the integer closer to 0.
a.mod(b) is the difference between a and a.floorDiv(b) * b. It’s either zero or has the same sign as b, while a % b
can have a different one.
fun main() {
114
//sampleStart
println("Floored division -5/3: ${(-5).floorDiv(3)}")
println( "Modulus: ${(-5).mod(3)}")
println("Truncated division -5/3: ${-5 / 3}")
println( "Remainder: ${-5 % 3}")
//sampleEnd
}
Duration
API
changes
The Duration API is Experimental. It may be dropped or changed at any time. Use it only for evaluation
purposes. We would appreciate hearing your feedback on it in YouTrack.
There is an experimental Duration class for representing duration amounts in different time units. In 1.5.0, the Duration
API has received the following changes:
Internal value representation now uses Long instead of Double to provide better precision.
There is a new API for conversion to a particular time unit in Long. It comes to replace the old API, which operates with
Double values and is now deprecated. For example, Duration.inWholeMinutes returns the value of the duration
expressed as Long and replaces Duration.inMinutes.
There are new companion functions for constructing a Duration from a number. For example, Duration.seconds(Int)
creates a Duration object representing an integer number of seconds. Old extension properties like Int.seconds are
now deprecated.
import kotlin.time.Duration
import kotlin.time.ExperimentalTime
@ExperimentalTime
fun main() {
//sampleStart
val duration = Duration.milliseconds(120000)
println("There are ${duration.inWholeSeconds} seconds in ${duration.inWholeMinutes} minutes")
//sampleEnd
}
New
API
for
getting
a
char
category
now
available
in
multiplatform
code
Kotlin 1.5.0 introduces the new API for getting a character’s category according to Unicode in multiplatform projects.
Several functions are now available in all the platforms and in the common code.
Char.isDigit()
Char.isLetter()
115
Char.isLetterOrDigit()
fun main() {
//sampleStart
val chars = listOf('a', '1', '+')
val (letterOrDigitList, notLetterOrDigitList) = chars.partition { it.isLetterOrDigit() }
println(letterOrDigitList) // [a, 1]
println(notLetterOrDigitList) // [+]
//sampleEnd
}
Char.isLowerCase()
Char.isUpperCase()
Char.isTitleCase()
fun main() {
//sampleStart
val chars = listOf('Dž', 'Lj', 'Nj', 'Dz', '1', 'A', 'a', '+')
val (titleCases, notTitleCases) = chars.partition { it.isTitleCase() }
println(titleCases) // [Dž, Lj, Nj, Dz]
println(notTitleCases) // [1, A, a, +]
//sampleEnd
}
Char.isDefined()
Char.isISOControl()
The property Char.category and its return type enum class CharCategory, which indicates a char's general category
according to Unicode, are now also available in multiplatform projects.
New
collections
function
firstNotNullOf()
The new firstNotNullOf() and firstNotNullOfOrNull() functions combine mapNotNull() with first() or firstOrNull(). They map
the original collection with the custom selector function and return the first non-null value. If there is no such value,
firstNotNullOf() throws an exception, and firstNotNullOfOrNull() returns null.
fun main() {
//sampleStart
val data = listOf("Kotlin", "1.5")
println(data.firstNotNullOf(String::toDoubleOrNull))
println(data.firstNotNullOfOrNull(String::toIntOrNull))
//sampleEnd
}
116
Strict
version
of
String?.toBoolean()
Two new functions introduce case-sensitive strict versions of the existing String?.toBoolean():
String.toBooleanStrict() throws an exception for all inputs except the literals true and false.
String.toBooleanStrictOrNull() returns null for all inputs except the literals true and false.
fun main() {
//sampleStart
println("true".toBooleanStrict())
println("1".toBooleanStrictOrNull())
// println("1".toBooleanStrict()) // Exception
//sampleEnd
}
kotlin-test
library
The kotlin-test library introduces some new features:
Simplified
test
dependencies
usage
in
multiplatform
projects
Now you can use the kotlin-test dependency to add dependencies for testing in the commonTest source set, and the
Gradle plugin will infer the corresponding platform dependencies for each test source set:
kotlin-test-junit for JVM source sets, see automatic choice of a testing framework for Kotlin/JVM source sets
Additionally, you can use the kotlin-test dependency in any shared or platform-specific source set.
An existing kotlin-test setup with explicit dependencies will continue to work both in Gradle and in Maven.
Automatic
selection
of
a
testing
framework
for
Kotlin/JVM
source
sets
The Gradle plugin now chooses and adds a dependency on a testing framework automatically. All you need to do is add
117
the dependency kotlin-test in the common source set.
Gradle uses JUnit 4 by default. Therefore, the kotlin("test") dependency resolves to the variant for JUnit 4, namely kotlin-
test-junit:
Kotlin
kotlin {
sourceSets {
val commonTest by getting {
dependencies {
implementation(kotlin("test")) // This brings the dependency
// on JUnit 4 transitively
}
}
}
}
Groovy
kotlin {
sourceSets {
commonTest {
dependencies {
implementation kotlin("test") // This brings the dependency
// on JUnit 4 transitively
}
}
}
}
You can choose JUnit 5 or TestNG by calling useJUnitPlatform() or useTestNG() in the test task:
tasks {
test {
// enable TestNG support
useTestNG()
// or
// enable JUnit Platform (a.k.a. JUnit 5) support
useJUnitPlatform()
}
}
You can disable automatic testing framework selection by adding the line kotlin.test.infer.jvm.variant=false to the
project’s gradle.properties.
Assertion
function
updates
This release brings new assertion functions and improves the existing ones.
118
The kotlin-test library now has the following features:
You can use the new assertIs<T> and assertIsNot<T> to check the type of a value:
@Test
fun testFunction() {
val s: Any = "test"
assertIs<String>(s) // throws AssertionError mentioning the actual type of s if the
assertion fails
// can now print s.length because of contract in assertIs
println("${s.length}")
}
Because of type erasure, this assert function only checks whether the value is of the List type in the following example
and doesn't check whether it's a list of the particular String element type: assertIs<List<String>>(value).
Comparing the container content for arrays, sequences, and arbitrary iterables
There is a new set of overloaded assertContentEquals() functions for comparing content for different collections that
don’t implement structural equality:
@Test
fun test() {
val expectedArray = arrayOf(1, 2, 3)
val actualArray = Array(3) { it + 1 }
assertContentEquals(expectedArray, actualArray)
}
New overloads to assertEquals() and assertNotEquals() for Double and Float numbers
There are new overloads for the assertEquals() function that make it possible to compare two Double or Float numbers
with absolute precision. The precision value is specified as the third parameter of the function:
@Test
fun test() {
val x = sin(PI)
// precision parameter
val tolerance = 0.000001
assertEquals(0.0, x, tolerance)
}
You can now check whether the collection or element contains something with the assertContains() function. You can
use it with Kotlin collections and elements that have the contains() operator, such as IntRange, String, and others:
@Test
119
fun test() {
val sampleList = listOf<String>("sample", "sample2")
val sampleString = "sample"
assertContains(sampleList, sampleString) // element in collection
assertContains(sampleString, "amp") // substring in string
}
From now on, you can use these as inline functions, so it's possible to call suspend functions inside a lambda
expression:
@Test
fun test() = runBlocking<Unit> {
val deferred = async { "Kotlin is nice" }
assertTrue("Kotlin substring should be present") {
deferred.await() .contains("Kotlin")
}
}
kotlinx
libraries
Along with Kotlin 1.5.0, we are releasing new versions of the kotlinx libraries:
kotlinx.coroutines 1.5.0-RC
kotlinx.serialization 1.2.1
kotlinx-datetime 0.2.0
Coroutines
1.5.0-RC
kotlinx.coroutines 1.5.0-RC is here with:
And more
Starting with Kotlin 1.5.0, experimental coroutines are disabled and the -Xcoroutines=experimental flag is no longer
supported.
Learn more in the changelog and the kotlinx.coroutines 1.5.0 release blog post.
120
Gif
Serialization
1.2.1
kotlinx.serialization 1.2.1 is here with:
And more
Learn more in the changelog and the kotlinx.serialization 1.2.1 release blog post.
121
Gif
dateTime
0.2.0
kotlinx-datetime 0.2.0 is here with:
And more
Learn more in the changelog and the kotlinx-datetime 0.2.0 release blog post.
Migrating
to
Kotlin
1.5.0
IntelliJ IDEA and Android Studio will suggest updating the Kotlin plugin to 1.5.0 once it is available.
To migrate existing projects to Kotlin 1.5.0, just change the Kotlin version to 1.5.0 and re-import your Gradle or Maven
project. Learn how to update to Kotlin 1.5.0.
To start a new project with Kotlin 1.5.0, update the Kotlin plugin and run the Project Wizard from File | New | Project.
The new command-line compiler is available for downloading on the GitHub release page.
Kotlin 1.5.0 is a feature release and therefore can bring incompatible changes to the language. Find the detailed list of
such changes in the Compatibility Guide for Kotlin 1.5.
122
What's
new
in
Kotlin
1.4.30
Release date: 3 February 2021
Kotlin 1.4.30 offers preview versions of new language features, promotes the new IR backend of the Kotlin/JVM compiler
to Beta, and ships various performance and functional improvements.
You can also learn about new features in this blog post.
Language
features
Kotlin 1.5.0 is going to deliver new language features – JVM records support, sealed interfaces, and Stable inline
classes. In Kotlin 1.4.30, you can try these features and improvements in preview mode. We’d be very grateful if you
share your feedback with us in the corresponding YouTrack tickets, as that will allow us to address it before the release
of 1.5.0.
To enable these language features and improvements in preview mode, you need to opt in by adding specific compiler
options. See the sections below for details.
Learn more about the new features preview in this blog post.
JVM
records
support
The JVM records feature is Experimental. It may be dropped or changed at any time. Opt-in is required (see the
details below), and you should use it only for evaluation purposes. We would appreciate your feedback on it in
YouTrack.
The JDK 16 release includes plans to stabilize a new Java class type called record. To provide all the benefits of Kotlin
and maintain its interoperability with Java, Kotlin is introducing experimental record class support.
You can use record classes that are declared in Java just like classes with properties in Kotlin. No additional steps are
required.
Starting with 1.4.30, you can declare the record class in Kotlin using the @JvmRecord annotation for a data class:
@JvmRecord
data class User(val name: String, val age: Int)
123
To try the preview version of JVM records, add the compiler options -Xjvm-enable-preview and -language-version 1.5.
We’re continuing to work on JVM records support and we’d be very grateful if you would share your feedback
with us using this YouTrack ticket.
Sealed
interfaces
Sealed interfaces are Experimental. They may be dropped or changed at any time. Opt-in is required (see the
details below), and you should use them only for evaluation purposes. We would appreciate your feedback on
them in YouTrack.
In Kotlin 1.4.30, we’re shipping the prototype of sealed interfaces. They complement sealed classes and make it
possible to build more flexible restricted class hierarchies.
They can serve as “internal†interfaces that cannot be implemented outside the same module. You can rely on that
fact, for example, to write exhaustive when expressions.
Another use-case: with sealed interfaces, you can inherit a class from two or more sealed superclasses.
To try the preview version of sealed interfaces, add the compiler option -language-version 1.5. Once you switch to this
version, you’ll be able to use the sealed modifier on interfaces. We’d be very grateful if you would share your
feedback with us using this YouTrack ticket.
124
Learn more about sealed interfaces.
Package-wide
sealed
class
hierarchies
Package-wide hierarchies of sealed classes are Experimental. They may be dropped or changed at any time.
Opt-in is required (see the details below), and you should use them only for evaluation purposes. We would
appreciate your feedback on them in YouTrack.
Sealed classes can now form more flexible hierarchies. They can have subclasses in all files of the same compilation unit
and the same package. Previously, all subclasses had to appear in the same file.
Direct subclasses may be top-level or nested inside any number of other named classes, named interfaces, or named
objects. The subclasses of a sealed class must have a name that is properly qualified – they cannot be local nor
anonymous objects.
To try package-wide hierarchies of sealed classes, add the compiler option -language-version 1.5. We’d be very
grateful if you would share your feedback with us using this YouTrack ticket.
Improved
inline
classes
Inline value classes are in Beta. They are almost stable, but migration steps may be required in the future. We'll
do our best to minimize any changes you have to make. We would appreciate your feedback on the inline
classes feature in YouTrack.
Kotlin 1.4.30 promotes inline classes to Beta and brings the following features and improvements to them:
Since inline classes are value-based, you can define them using the value modifier. The inline and value modifiers are
now equivalent to each other. In future Kotlin versions, we’re planning to deprecate the inline modifier.
From now on, Kotlin requires the @JvmInline annotation before a class declaration for the JVM backend:
Inline classes can have init blocks. You can add code to be executed right after the class is instantiated:
125
@JvmInline
value class Negative(val x: Int) {
init {
require(x < 0) { }
}
}
Calling functions with inline classes from Java code: before Kotlin 1.4.30, you couldn't call functions that accept inline
classes from Java because of mangling. From now on, you can disable mangling manually. To call such functions from
Java code, you should add the @JvmName annotation before the function declaration:
@JvmName("computeUInt")
fun compute(x: UInt) { }
In this release, we’ve changed the mangling scheme for functions to fix the incorrect behavior. These changes led
to ABI changes.
Starting with 1.4.30, the Kotlin compiler uses a new mangling scheme by default. Use the -Xuse-14-inline-classes-
mangling-scheme compiler flag to force the compiler to use the old 1.4.0 mangling scheme and preserve binary
compatibility.
Kotlin 1.4.30 promotes inline classes to Beta and we are planning to make them Stable in future releases. We’d be
very grateful if you would share your feedback with us using this YouTrack ticket.
To try the preview version of inline classes, add the compiler option -Xinline-classes or -language-version 1.5.
Kotlin/JVM
JVM
IR
compiler
backend
reaches
Beta
The IR-based compiler backend for Kotlin/JVM, which was presented in 1.4.0 in Alpha, has reached Beta. This is the last
pre-stable level before the IR backend becomes the default for the Kotlin/JVM compiler.
We’re now dropping the restriction on consuming binaries produced by the IR compiler. Previously, you could use
code compiled by the new JVM IR backend only if you had enabled the new backend. Starting from 1.4.30, there is no
such limitation, so you can use the new backend to build components for third-party use, such as libraries. Try the Beta
version of the new backend and share your feedback in our issue tracker.
To enable the new JVM IR backend, add the following lines to the project’s configuration file:
In Gradle:
126
Kotlin
tasks.withType(org.jetbrains.kotlin.gradle.dsl.KotlinJvmCompile::class) {
kotlinOptions.useIR = true
}
Groovy
tasks.withType(org.jetbrains.kotlin.gradle.dsl.KotlinJvmCompile) {
kotlinOptions.useIR = true
}
In Maven:
<configuration>
<args>
<arg>-Xuse-ir</arg>
</args>
</configuration>
Learn more about the changes that the JVM IR backend brings in this blog post.
Kotlin/Native
Performance
improvements
Kotlin/Native has received a variety of performance improvements in 1.4.30, which has resulted in faster compilation
times. For example, the time required to rebuild the framework in the KMM Networking and Data Storage sample has
decreased from 9.5 seconds (in 1.4.10) to 4.5 seconds (in 1.4.30).
Apple
watchOS
64-bit
simulator
target
The x86 simulator target has been deprecated for watchOS since version 7.0. To keep up with the latest watchOS
versions, Kotlin/Native has the new target watchosX64 for running the simulator on 64-bit architecture.
Support
for
Xcode
12.2
libraries
We have added support for the new libraries delivered with Xcode 12.2. You can now use them from Kotlin code.
Kotlin/JS
127
Lazy
initialization
of
top-level
properties
Lazy initialization of top-level properties is Experimental. It may be dropped or changed at any time. Opt-in is
required (see the details below), and you should use it only for evaluation purposes. We would appreciate your
feedback on it in YouTrack.
The IR backend for Kotlin/JS is receiving a prototype implementation of lazy initialization for top-level properties. This
reduces the need to initialize all top-level properties when the application starts, and it should significantly improve
application start-up times.
We’ll keep working on the lazy initialization, and we ask you to try the current prototype and share your thoughts and
results in this YouTrack ticket or the #javascript channel in the official Kotlin Slack (get an invite here).
To use the lazy initialization, add the -Xir-property-lazy-initialization compiler option when compiling the code with the JS
IR compiler.
Gradle
project
improvements
Support
the
Gradle
configuration
cache
Starting with 1.4.30, the Kotlin Gradle plugin supports the configuration cache feature. It speeds up the build process:
once you run the command, Gradle executes the configuration phase and calculates the task graph. Gradle caches the
result and reuses it for subsequent builds.
To start using this feature, you can use the Gradle command or set up the IntelliJ based IDE.
Standard
library
Locale-agnostic
API
for
upper/lowercasing
text
The locale-agnostic API feature is Experimental. It may be dropped or changed at any time. Use it only for
evaluation purposes. We would appreciate your feedback on it in YouTrack.
This release introduces the experimental locale-agnostic API for changing the case of strings and characters. The current
toLowerCase(), toUpperCase(), capitalize(), decapitalize() API functions are locale-sensitive. This means that different
platform locale settings can affect code behavior. For example, in the Turkish locale, when the string “kotlin†is
converted using toUpperCase, the result is "KOTLİN", not "KOTLIN".
// current API
println("Needs to be capitalized".toUpperCase()) // NEEDS TO BE CAPITALIZED
128
// new API
println("Needs to be capitalized".uppercase()) // NEEDS TO BE CAPITALIZED
Earlier
versions 1.4.30
alternative
String.toUpperCase() String.uppercase()
String.toLowerCase() String.lowercase()
Earlier
versions 1.4.30
alternative
Char.toUpperCase() Char.uppercaseChar():
Char
Char.uppercase(): String
For Kotlin/JVM, there are also overloaded uppercase(), lowercase(), and titlecase() functions with an explicit
Locale parameter.
See the full list of changes to the text processing functions in KEEP.
Clear
Char-to-code
and
Char-to-digit
conversions
The unambiguous API for the Char conversion feature is Experimental. It may be dropped or changed at any
time. Use it only for evaluation purposes. We would appreciate your feedback on it in YouTrack.
129
The current Char to numbers conversion functions, which return UTF-16 codes expressed in different numeric types, are
often confused with the similar String-to-Int conversion, which returns the numeric value of a string:
"4".toInt() // returns 4
'4'.toInt() // returns 52
// and there was no common function that would return the numeric value 4 for Char '4'
To avoid this confusion we've decided to separate Char conversions into two following sets of clearly named functions:
Functions to get the integer code of Char and to construct Char from the given code:
An extension function for Int to convert the non-negative single digit it represents to the corresponding Char
representation:
Serialization
updates
Along with Kotlin 1.4.30, we are releasing kotlinx.serialization 1.1.0-RC, which includes some new features:
Inline
classes
serialization
support
Starting with Kotlin 1.4.30, you can make inline classes serializable:
@Serializable
inline class Color(val rgb: Int)
130
The serialization framework does not box serializable inline classes when they are used in other serializable classes.
Unsigned
primitive
type
serialization
support
Starting from 1.4.30, you can use standard JSON serializers of kotlinx.serialization for unsigned primitive types: UInt,
ULong, UByte, and UShort:
@Serializable
class Counter(val counted: UByte, val description: String)
fun main() {
val counted = 239.toUByte()
println(Json.encodeToString(Counter(counted, "tries")))
}
What's
new
in
Kotlin
1.3
Release date: 29 October 2018
Coroutines
release
After some long and extensive battle testing, coroutines are now released! It means that from Kotlin 1.3 the language
support and the API are fully stable. Check out the new coroutines overview page.
Kotlin 1.3 introduces callable references on suspend-functions and support of coroutines in the reflection API.
Kotlin/Native
Kotlin 1.3 continues to improve and polish the Native target. See the Kotlin/Native overview for details.
Multiplatform
projects
In 1.3, we've completely reworked the model of multiplatform projects in order to improve expressiveness and flexibility,
and to make sharing common code easier. Also, Kotlin/Native is now supported as one of the targets!
In the old model, common and platform-specific code needed to be placed in separate modules, linked by expectedBy
dependencies. Now, common and platform-specific code is placed in different source roots of the same module,
making projects easier to configure.
131
There is now a large number of preset platform configurations for different supported platforms.
The dependencies configuration has been changed; dependencies are now specified separately for each source root.
Source sets can now be shared between an arbitrary subset of platforms (for example, in a module that targets JS,
Android and iOS, you can have a source set that is shared only between Android and iOS).
Contracts
The Kotlin compiler does extensive static analysis to provide warnings and reduce boilerplate. One of the most notable
features is smartcasts — with the ability to perform a cast automatically based on the performed type checks:
However, as soon as these checks are extracted in a separate function, all the smartcasts immediately disappear:
To improve the behavior in such cases, Kotlin 1.3 introduces experimental mechanism called contracts.
Contracts allow a function to explicitly describe its behavior in a way which is understood by the compiler. Currently, two
wide classes of cases are supported:
Improving smartcasts analysis by declaring the relation between a function's call outcome and the passed arguments
values:
132
fun synchronize(lock: Any?, block: () -> Unit) {
// It tells the compiler:
// "This function will invoke 'block' here and now, and exactly one time"
contract { callsInPlace(block, EXACTLY_ONCE) }
}
fun foo() {
val x: Int
synchronize(lock) {
x = 42 // Compiler knows that lambda passed to 'synchronize' is called
// exactly once, so no reassignment is reported
}
println(x) // Compiler knows that lambda will be definitely called, performing
// initialization, so 'x' is considered to be initialized here
}
Contracts
in
stdlib
stdlib already makes use of contracts, which leads to improvements in the analyses described above. This part of
contracts is stable, meaning that you can benefit from the improved analysis right now without any additional opt-ins:
//sampleStart
fun bar(x: String?) {
if (!x.isNullOrEmpty()) {
println("length of '$x' is ${x.length}") // Yay, smartcast to not-null!
}
}
//sampleEnd
fun main() {
bar(null)
bar("42")
}
Custom
contracts
It is possible to declare contracts for your own functions, but this feature is experimental, as the current syntax is in a
state of early prototype and will most probably be changed. Also please note that currently the Kotlin compiler does not
verify contracts, so it's the responsibility of the programmer to write correct and sound contracts.
Custom contracts are introduced by a call to contract stdlib function, which provides DSL scope:
See the details on the syntax as well as the compatibility notice in the KEEP.
133
Capturing
when
subject
in
a
variable
In Kotlin 1.3, it is now possible to capture the when subject into a variable:
fun Request.getBody() =
when (val response = executeRequest()) {
is Success -> response.body
is HttpError -> throw HttpException(response.status)
}
While it was already possible to extract this variable just before when, val in when has its scope properly restricted to the
body of when, and so preventing namespace pollution. See the full documentation on when here.
@JvmStatic
and
@JvmField
in
companions
of
interfaces
With Kotlin 1.3, it is possible to mark members of a companion object of interfaces with annotations @JvmStatic and
@JvmField. In the classfile, such members will be lifted to the corresponding interface and marked as static.
interface Foo {
companion object {
@JvmField
val answer: Int = 42
@JvmStatic
fun sayHello() {
println("Hello, world!")
}
}
}
interface Foo {
public static int answer = 42;
public static void sayHello() {
// ...
}
}
Nested
declarations
in
annotation
classes
In Kotlin 1.3, it is possible for annotations to have nested classes, interfaces, objects, and companions:
134
annotation class Bar
companion object {
fun foo(): Int = 42
val bar: Int = 42
}
}
Parameterless
main
By convention, the entry point of a Kotlin program is a function with a signature like main(args: Array<String>), where args
represent the command-line arguments passed to the program. However, not every application supports command-line
arguments, so this parameter often ends up not being used.
Kotlin 1.3 introduced a simpler form of main which takes no parameters. Now “Hello, World†in Kotlin is 19
characters shorter!
fun main() {
println("Hello, world!")
}
Functions
with
big
arity
In Kotlin, functional types are represented as generic classes taking a different number of parameters: Function0<R>,
Function1<P0, R>, Function2<P0, P1, R>, ... This approach has a problem in that this list is finite, and it currently ends
with Function22.
Kotlin 1.3 relaxes this limitation and adds support for functions with bigger arity:
fun trueEnterpriseComesToKotlin(block: (Any, Any, ... /* 42 more */, Any) -> Any) {
block(Any(), Any(), ..., Any())
}
Progressive
mode
Kotlin cares a lot about stability and backward compatibility of code: Kotlin compatibility policy says that breaking
changes (e.g., a change which makes the code that used to compile fine, not compile anymore) can be introduced only in
the major releases (1.2, 1.3, etc.).
We believe that a lot of users could use a much faster cycle where critical compiler bug fixes arrive immediately, making
the code more safe and correct. So, Kotlin 1.3 introduces the progressive compiler mode, which can be enabled by
passing the argument -progressive to the compiler.
In the progressive mode, some fixes in language semantics can arrive immediately. All these fixes have two important
properties:
135
They preserve backward compatibility of source code with older compilers, meaning that all the code which is
compilable by the progressive compiler will be compiled fine by non-progressive one.
They only make code safer in some sense — e.g., some unsound smartcast can be forbidden, behavior of the
generated code may be changed to be more predictable/stable, and so on.
Enabling the progressive mode can require you to rewrite some of your code, but it shouldn't be too much — all the fixes
enabled under progressive are carefully handpicked, reviewed, and provided with tooling migration assistance. We expect
that the progressive mode will be a nice choice for any actively maintained codebases which are updated to the latest
language versions quickly.
Inline
classes
Inline classes are in Alpha. They may change incompatibly and require manual migration in the future. We
appreciate your feedback on it in YouTrack. See details in the reference.
Kotlin 1.3 introduces a new kind of declaration — inline class. Inline classes can be viewed as a restricted version of the
usual classes, in particular, inline classes must have exactly one property:
The Kotlin compiler will use this restriction to aggressively optimize runtime representation of inline classes and substitute
their instances with the value of the underlying property where possible removing constructor calls, GC pressure, and
enabling other optimizations:
Unsigned
integers
Unsigned integers are in Beta. Their implementation is almost stable, but migration steps may be required in the
future. We'll do our best to minimize any changes you will have to make.
136
Kotlin 1.3 introduces unsigned integer types:
Most of the functionality of signed types are supported for unsigned counterparts too:
fun main() {
//sampleStart
// You can define unsigned types using literal suffixes
val uint = 42u
val ulong = 42uL
val ubyte: UByte = 255u
// You can convert signed types to unsigned and vice versa via stdlib extensions:
val int = uint.toInt()
val byte = ubyte.toByte()
val ulong2 = byte.toULong()
@JvmDefault
@JvmDefault is Experimental. It may be dropped or changed at any time. Use it only for evaluation purposes.
We appreciate your feedback on it in YouTrack.
Kotlin targets a wide range of the Java versions, including Java 6 and Java 7, where default methods in the interfaces are
not allowed. For your convenience, the Kotlin compiler works around that limitation, but this workaround isn't compatible
with the default methods, introduced in Java 8.
This could be an issue for Java-interoperability, so Kotlin 1.3 introduces the @JvmDefault annotation. Methods annotated
with this annotation will be generated as default methods for JVM:
interface Foo {
137
// Will be generated as 'default' method
@JvmDefault
fun foo(): Int = 42
}
Warning! Annotating your API with @JvmDefault has serious implications on binary compatibility. Make sure to
carefully read the reference page before using @JvmDefault in production.
Standard
library
Multiplatform
random
Prior to Kotlin 1.3, there was no uniform way to generate random numbers on all platforms — we had to resort to
platform-specific solutions like java.util.Random on JVM. This release fixes this issue by introducing the class
kotlin.random.Random, which is available on all platforms:
import kotlin.random.Random
fun main() {
//sampleStart
val number = Random.nextInt(42) // number is in range [0, limit)
println(number)
//sampleEnd
}
isNullOrEmpty
and
orEmpty
extensions
isNullOrEmpty and orEmpty extensions for some types are already present in stdlib. The first one returns true if the
receiver is null or empty, and the second one falls back to an empty instance if the receiver is null. Kotlin 1.3 provides
similar extensions on collections, maps, and arrays of objects.
Copy
elements
between
two
existing
arrays
The array.copyInto(targetArray, targetOffset, startIndex, endIndex) functions for the existing array types, including the
unsigned arrays, make it easier to implement array-based containers in pure Kotlin.
fun main() {
//sampleStart
val sourceArr = arrayOf("k", "o", "t", "l", "i", "n")
val targetArr = sourceArr.copyInto(arrayOfNulls<String>(6), 3, startIndex = 3, endIndex = 6)
println(targetArr.contentToString())
sourceArr.copyInto(targetArr, startIndex = 0, endIndex = 3)
println(targetArr.contentToString())
//sampleEnd
}
138
associateWith
It is quite a common situation to have a list of keys and want to build a map by associating each of these keys with some
value. It was possible to do it before with the associate { it to getValue(it) } function, but now we’re introducing a more
efficient and easy to explore alternative: keys.associateWith { getValue(it) }.
fun main() {
//sampleStart
val keys = 'a'..'f'
val map = keys.associateWith { it.toString().repeat(5).capitalize() }
map.forEach { println(it) }
//sampleEnd
}
ifEmpty
and
ifBlank
functions
Collections, maps, object arrays, char sequences, and sequences now have an ifEmpty function, which allows specifying
a fallback value that will be used instead of the receiver if it is empty:
fun main() {
//sampleStart
fun printAllUppercase(data: List<String>) {
val result = data
.filter { it.all { c -> c.isUpperCase() } }
.ifEmpty { listOf("<no uppercase>") }
result.forEach { println(it) }
}
printAllUppercase(listOf("foo", "Bar"))
printAllUppercase(listOf("FOO", "BAR"))
//sampleEnd
}
Char sequences and strings in addition have an ifBlank extension that does the same thing as ifEmpty but checks for a
string being all whitespace instead of empty.
fun main() {
//sampleStart
val s = " \n"
println(s.ifBlank { "<blank>" })
println(s.ifBlank { null })
//sampleEnd
}
Sealed
classes
in
reflection
We’ve added a new API to kotlin-reflect that can be used to enumerate all the direct subtypes of a sealed class,
namely KClass.sealedSubclasses.
Smaller
changes
139
Boolean type now has companion.
Tooling
Code
style
support
in
IDE
Kotlin 1.3 introduces support for the recommended code style in IntelliJ IDEA. Check out this page for the migration
guidelines.
kotlinx.serialization
kotlinx.serialization is a library which provides multiplatform support for (de)serializing objects in Kotlin. Previously, it was
a separate project, but since Kotlin 1.3, it ships with the Kotlin compiler distribution on par with the other compiler
plugins. The main difference is that you don't need to manually watch out for the Serialization IDE Plugin being
compatible with the Kotlin IDE plugin version you're using: now the Kotlin IDE plugin already includes serialization!
Even though kotlinx.serialization now ships with the Kotlin Compiler distribution, it is still considered to be an
experimental feature in Kotlin 1.3.
Scripting
update
Scripting is Experimental. It may be dropped or changed at any time. Use it only for evaluation purposes. We
appreciate your feedback on it in YouTrack.
Kotlin 1.3 continues to evolve and improve scripting API, introducing some experimental support for scripts
customization, such as adding external properties, providing static or dynamic dependencies, and so on.
Scratches
support
Kotlin 1.3 introduces support for runnable Kotlin scratch files. Scratch file is a kotlin script file with the .kts extension that
you can run and get evaluation results directly in the editor.
140
Consult the general Scratches documentation for details.
What's
new
in
Kotlin
1.2
Release date: 28 November 2017
Table
of
contents
Multiplatform projects
Standard library
JVM backend
JavaScript backend
Multiplatform
projects
(experimental)
Multiplatform projects are a new experimental feature in Kotlin 1.2, allowing you to reuse code between target platforms
supported by Kotlin – JVM, JavaScript, and (in the future) Native. In a multiplatform project, you have three kinds of
modules:
A common module contains code that is not specific to any platform, as well as declarations without implementation
of platform-dependent APIs.
A platform module contains implementations of platform-dependent declarations in the common module for a specific
platform, as well as other platform-dependent code.
A regular module targets a specific platform and can either be a dependency of platform modules or depend on
platform modules.
When you compile a multiplatform project for a specific platform, the code for both the common and platform-specific
parts is generated.
A key feature of the multiplatform project support is the possibility to express dependencies of common code on
platform-specific parts through expected and actual declarations. An expected declaration specifies an API (class,
interface, annotation, top-level declaration etc.). An actual declaration is either a platform-dependent implementation of
the API or a typealias referring to an existing implementation of the API in an external library. Here's an example:
141
fun greet() {
// usage of the expected API:
val greeting = hello("multiplatform world")
println(greeting)
}
See the multiplatform programming documentation for details and steps to build a multiplatform project.
Other
language
features
Array
literals
in
annotations
Starting with Kotlin 1.2, array arguments for annotations can be passed with the new array literal syntax instead of the
arrayOf function:
Lateinit
top-level
properties
and
local
variables
The lateinit modifier can now be used on top-level properties and local variables. The latter can be used, for example,
when a lambda passed as a constructor argument to one object refers to another object which has to be defined later:
142
third = Node(3, next = { first })
Check
whether
a
lateinit
var
is
initialized
You can now check whether a lateinit var has been initialized using isInitialized on the property reference:
class Foo {
lateinit var lateinitVar: String
fun initializationLogic() {
//sampleStart
println("isInitialized before assignment: " + this::lateinitVar.isInitialized)
lateinitVar = "value"
println("isInitialized after assignment: " + this::lateinitVar.isInitialized)
//sampleEnd
}
}
Inline
functions
with
default
functional
parameters
Inline functions are now allowed to have default values for their inlined functional parameters:
//sampleStart
inline fun <E> Iterable<E>.strings(transform: (E) -> String = { it.toString() }) =
map { transform(it) }
Information
from
explicit
casts
is
used
for
type
inference
The Kotlin compiler can now use information from type casts in type inference. If you’re calling a generic method that
returns a type parameter T and casting the return value to a specific type Foo, the compiler now understands that T for
this call needs to be bound to the type Foo.
This is particularly important for Android developers, since the compiler can now correctly analyze generic findViewById
calls in Android API level 26:
143
val button = findViewById(R.id.button) as Button
Smart
cast
improvements
When a variable is assigned from a safe call expression and checked for null, the smart cast is now applied to the safe
call receiver as well:
Also, smart casts in a lambda are now allowed for local variables that are only modified before the lambda:
run {
if (x != null) {
println(x.length) // x is smart cast to String
}
}
//sampleEnd
}
Support
for
::foo
as
a
shorthand
for
this::foo
A bound callable reference to a member of this can now be written without explicit receiver, ::foo instead of this::foo. This
also makes callable references more convenient to use in lambdas where you refer to a member of the outer receiver.
144
Breaking
change:
sound
smart
casts
after
try
blocks
Earlier, Kotlin used assignments made inside a try block for smart casts after the block, which could break type- and null-
safety and lead to runtime failures. This release fixes this issue, making the smart casts more strict, but breaking some
code that relied on such smart casts.
To switch to the old smart casts behavior, pass the fallback flag -Xlegacy-smart-cast-after-try as the compiler argument.
It will become deprecated in Kotlin 1.3.
Deprecation:
data
classes
overriding
copy
When a data class derived from a type that already had the copy function with the same signature, the copy
implementation generated for the data class used the defaults from the supertype, leading to counter-intuitive behavior, or
failed at runtime if there were no default parameters in the supertype.
Inheritance that leads to a copy conflict has become deprecated with a warning in Kotlin 1.2 and will be an error in Kotlin
1.3.
Deprecation:
nested
types
in
enum
entries
Inside enum entries, defining a nested type that is not an inner class has been deprecated due to issues in the
initialization logic. This causes a warning in Kotlin 1.2 and will become an error in Kotlin 1.3.
Deprecation:
single
named
argument
for
vararg
For consistency with array literals in annotations, passing a single item for a vararg parameter in the named form
(foo(items = i)) has been deprecated. Please use the spread operator with the corresponding array factory functions:
foo(items = *intArrayOf(1))
There is an optimization that removes redundant arrays creation in such cases, which prevents performance degradation.
The single-argument form produces warnings in Kotlin 1.2 and is to be dropped in Kotlin 1.3.
Deprecation:
inner
classes
of
generic
classes
extending
Throwable
Inner classes of generic types that inherit from Throwable could violate type-safety in a throw-catch scenario and thus
have been deprecated, with a warning in Kotlin 1.2 and an error in Kotlin 1.3.
Deprecation:
mutating
backing
field
of
a
read-only
property
Mutating the backing field of a read-only property by assigning field = ... in the custom getter has been deprecated, with a
warning in Kotlin 1.2 and an error in Kotlin 1.3.
Standard
library
145
Kotlin
standard
library
artifacts
and
split
packages
The Kotlin standard library is now fully compatible with the Java 9 module system, which forbids split packages (multiple
jar files declaring classes in the same package). In order to support that, new artifacts kotlin-stdlib-jdk7 and kotlin-stdlib-
jdk8 are introduced, which replace the old kotlin-stdlib-jre7 and kotlin-stdlib-jre8.
The declarations in the new artifacts are visible under the same package names from the Kotlin point of view, but have
different package names for Java. Therefore, switching to the new artifacts will not require any changes to your source
code.
Another change made to ensure compatibility with the new module system is removing the deprecated declarations in the
kotlin.reflect package from the kotlin-reflect library. If you were using them, you need to switch to using the declarations in
the kotlin.reflect.full package, which is supported since Kotlin 1.1.
windowed,
chunked,
zipWithNext
New extensions for Iterable<T>, Sequence<T>, and CharSequence cover such use cases as buffering or batch
processing (chunked), sliding window and computing sliding average (windowed) , and processing pairs of subsequent
items (zipWithNext):
println("items: $items\n")
fill,
replaceAll,
shuffle/shuffled
A set of extension functions was added for manipulating lists: fill, replaceAll and shuffle for MutableList, and shuffled for
read-only List:
146
println("Items doubled: $items")
items.fill(5)
println("Items filled with 5: $items")
//sampleEnd
}
Math
operations
in
kotlin-stdlib
Satisfying the longstanding request, Kotlin 1.2 adds the kotlin.math API for math operations that is common for JVM and
JS and contains the following:
Constants: PI and E
Trigonometric: cos, sin, tan and inverse of them: acos, asin, atan, atan2
Hyperbolic: cosh, sinh, tanh and their inverse: acosh, asinh, atanh
Rounding:
ceil, floor, truncate, round (half to even) functions
Binary representation:
ulp extension property
The same set of functions (but without constants) is also available for Float arguments.
Operators
and
conversions
for
BigInteger
and
BigDecimal
Kotlin 1.2 introduces a set of functions for operating with BigInteger and BigDecimal and creating them from other
numeric types. These are:
147
toBigDecimal for Int, Long, Float, Double, and BigInteger
Floating
point
to
bits
conversions
New functions were added for converting Double and Float to and from their bit representations:
toBits and toRawBits returning Long for Double and Int for Float
Double.fromBits and Float.fromBits for creating floating point numbers from the bit representation
Regex
is
now
serializable
The kotlin.text.Regex class has become Serializable and can now be used in serializable hierarchies.
Closeable.use
calls
Throwable.addSuppressed
if
available
The Closeable.use function calls Throwable.addSuppressed when an exception is thrown during closing the resource
after some other exception.
JVM
backend
Constructor
calls
normalization
Ever since version 1.0, Kotlin supported expressions with complex control flow, such as try-catch expressions and inline
function calls. Such code is valid according to the Java Virtual Machine specification. Unfortunately, some bytecode
processing tools do not handle such code quite well when such expressions are present in the arguments of constructor
calls.
To mitigate this problem for the users of such bytecode processing tools, we’ve added a command-line compiler
option (-Xnormalize-constructor-calls=MODE) that tells the compiler to generate more Java-like bytecode for such
constructs. Here MODE is one of:
disable (default) – generate bytecode in the same way as in Kotlin 1.0 and 1.1.
enable – generate Java-like bytecode for constructor calls. This can change the order in which the classes are
loaded and initialized.
preserve-class-initialization – generate Java-like bytecode for constructor calls, ensuring that the class initialization
order is preserved. This can affect overall performance of your application; use it only if you have some complex state
shared between multiple classes and updated on class initialization.
148
The “manual†workaround is to store the values of sub-expressions with control flow in variables, instead of
evaluating them directly inside the call arguments. It’s similar to -Xnormalize-constructor-calls=enable.
Java-default
method
calls
Before Kotlin 1.2, interface members overriding Java-default methods while targeting JVM 1.6 produced a warning on
super calls: Super calls to Java default methods are deprecated in JVM target 1.6. Recompile with '-jvm-target 1.8'. In
Kotlin 1.2, there's an error instead, thus requiring any such code to be compiled with JVM target 1.8.
Breaking
change:
consistent
behavior
of
x.equals(null)
for
platform
types
Calling x.equals(null) on a platform type that is mapped to a Java primitive (Int!, Boolean!, Short!, Long!, Float!, Double!,
Char!) incorrectly returned true when x was null. Starting with Kotlin 1.2, calling x.equals(...) on a null value of a platform
type throws an NPE (but x == ... does not).
To return to the pre-1.2 behavior, pass the flag -Xno-exception-on-explicit-equals-for-boxed-null to the compiler.
Breaking
change:
fix
for
platform
null
escaping
through
an
inlined
extension
receiver
Inline extension functions that were called on a null value of a platform type did not check the receiver for null and would
thus allow null to escape into the other code. Kotlin 1.2 forces this check at the call sites, throwing an exception if the
receiver is null.
To switch to the old behavior, pass the fallback flag -Xno-receiver-assertions to the compiler.
JavaScript
backend
TypedArrays
support
enabled
by
default
The JS typed arrays support that translates Kotlin primitive arrays, such as IntArray, DoubleArray, into JavaScript typed
arrays, that was previously an opt-in feature, has been enabled by default.
Tools
Warnings
as
errors
The compiler now provides an option to treat all warnings as errors. Use -Werror on the command line, or the following
Gradle snippet:
compileKotlin {
kotlinOptions.allWarningsAsErrors = true
}
149
What's
new
in
Kotlin
1.1
Release date: 15 February 2016
Table
of
contents
Coroutines
Standard library
JVM backend
JavaScript backend
JavaScript
Starting with Kotlin 1.1, the JavaScript target is no longer considered experimental. All language features are supported,
and there are many new tools for integration with the frontend development environment. See below for a more detailed
list of changes.
Coroutines
(experimental)
The key new feature in Kotlin 1.1 is coroutines, bringing the support of async/ await, yield, and similar programming
patterns. The key feature of Kotlin's design is that the implementation of coroutine execution is part of the libraries, not
the language, so you aren't bound to any specific programming paradigm or concurrency library.
A coroutine is effectively a light-weight thread that can be suspended and resumed later. Coroutines are supported
through suspending functions: a call to such a function can potentially suspend a coroutine, and to start a new coroutine
we usually use an anonymous suspending functions (i.e. suspending lambdas).
150
// and then show it in UI
showImage(image)
}
Here, async { ... } starts a coroutine and, when we use await(), the execution of the coroutine is suspended while the
operation being awaited is executed, and is resumed (possibly on a different thread) when the operation being awaited
completes.
The standard library uses coroutines to support lazily generated sequences with yield and yieldAll functions. In such a
sequence, the block of code that returns sequence elements is suspended after each element has been retrieved, and
resumed when the next element is requested. Here's an example:
import kotlin.coroutines.experimental.*
Run the code above to see the result. Feel free to edit it and run again!
For more information, please refer to the coroutines documentation and tutorial.
Note that coroutines are currently considered an experimental feature, meaning that the Kotlin team is not committing to
supporting the backwards compatibility of this feature after the final 1.1 release.
Other
language
features
Type
aliases
A type alias allows you to define an alternative name for an existing type. This is most useful for generic types such as
collections, as well as for function types. Here is an example:
//sampleStart
typealias OscarWinners = Map<String, String>
// Note that the type names (initial and the type alias) are interchangeable:
fun checkLaLaLandIsTheBestMovie(oscarWinners: Map<String, String>) =
oscarWinners["Best picture"] == "La La Land"
151
//sampleEnd
See the type aliases documentation and KEEP for more details.
Bound
callable
references
You can now use the :: operator to get a member reference pointing to a method or property of a specific object instance.
Previously this could only be expressed with a lambda. Here's an example:
//sampleStart
val numberRegex = "\\d+".toRegex()
val numbers = listOf("abc", "123", "456").filter(numberRegex::matches)
//sampleEnd
Sealed
and
data
classes
Kotlin 1.1 removes some of the restrictions on sealed and data classes that were present in Kotlin 1.0. Now you can
define subclasses of a top-level sealed class on the top level in the same file, and not just as nested classes of the sealed
class. Data classes can now extend other classes. This can be used to define a hierarchy of expression classes nicely and
cleanly:
//sampleStart
sealed class Expr
152
is Sum -> eval(expr.e1) + eval(expr.e2)
NotANumber -> Double.NaN
}
val e = eval(Sum(Const(1.0), Const(2.0)))
//sampleEnd
Read the sealed classes documentation or KEEPs for sealed class and data class for more detail.
Destructuring
in
lambdas
You can now use the destructuring declaration syntax to unpack the arguments passed to a lambda. Here's an example:
Read the destructuring declarations documentation and KEEP for more details.
Underscores
for
unused
parameters
For a lambda with multiple parameters, you can use the _ character to replace the names of the parameters you don't
use:
//sampleStart
map.forEach { _, value -> println("$value!") }
//sampleEnd
}
153
val (_, status) = getResult()
//sampleEnd
println("status is '$status'")
}
Underscores
in
numeric
literals
Just as in Java 8, Kotlin now allows to use underscores in numeric literals to separate groups of digits:
//sampleStart
val oneMillion = 1_000_000
val hexBytes = 0xFF_EC_DE_5E
val bytes = 0b11010010_01101001_10010100_10010010
//sampleEnd
Shorter
syntax
for
properties
For properties with the getter defined as an expression body, the property type can now be omitted:
//sampleStart
data class Person(val name: String, val age: Int) {
val isAdult get() = age >= 20 // Property type inferred to be 'Boolean'
}
//sampleEnd
fun main(args: Array<String>) {
val akari = Person("Akari", 26)
println("$akari.isAdult = ${akari.isAdult}")
}
Inline
property
accessors
You can now mark property accessors with the inline modifier if the properties don't have a backing field. Such accessors
are compiled in the same way as inline functions.
//sampleStart
public val <T> List<T>.lastIndex: Int
inline get() = this.size - 1
//sampleEnd
154
// the getter will be inlined
println("Last index of $list is ${list.lastIndex}")
}
You can also mark the entire property as inline- then the modifier is applied to both accessors.
Read the inline functions documentation and KEEP for more details.
Local
delegated
properties
You can now use the delegated property syntax with local variables. One possible use is defining a lazily evaluated local
variable:
import java.util.Random
Interception
of
delegated
property
binding
For delegated properties, it is now possible to intercept delegate to property binding using the provideDelegate operator.
For example, if we want to check the property name before binding, we can write something like this:
class MyUI {
val image by bindResource(ResourceID.image_id)
val text by bindResource(ResourceID.text_id)
}
155
The provideDelegate method will be called for each property during the creation of a MyUI instance, and it can perform
the necessary validation right away.
Generic
enum
value
access
It is now possible to enumerate the values of an enum class in a generic way.
//sampleStart
enum class RGB { RED, GREEN, BLUE }
Scope
control
for
implicit
receivers
in
DSLs
The @DslMarker annotation allows to restrict the use of receivers from outer scopes in a DSL context. Consider the
canonical HTML builder example:
table {
tr {
td { + "Text" }
}
}
In Kotlin 1.0, code in the lambda passed to td has access to three implicit receivers: the one passed to table, to tr and to
td. This allows you to call methods that make no sense in the context - for example to call tr inside td and thus to put a
<tr> tag in a <td>.
In Kotlin 1.1, you can restrict that, so that only methods defined on the implicit receiver of td will be available inside the
lambda passed to td. You do that by defining your annotation marked with the @DslMarker meta-annotation and applying
it to the base class of the tag classes.
Read the type safe builders documentation and KEEP for more details.
rem
operator
The mod operator is now deprecated, and rem is used instead. See this issue for motivation.
156
Standard
library
String
to
number
conversions
There is a bunch of new extensions on the String class to convert it to a number without throwing an exception on invalid
number: String.toIntOrNull(): Int?, String.toDoubleOrNull(): Double? etc.
Also integer conversion functions, like Int.toString(), String.toInt(), String.toIntOrNull(), each got an overload with radix
parameter, which allows to specify the base of conversion (2 to 36).
onEach()
onEach is a small, but useful extension function for collections and sequences, which allows to perform some action,
possibly with side-effects, on each element of the collection/sequence in a chain of operations. On iterables it behaves
like forEach but also returns the iterable instance further. And on sequences it returns a wrapping sequence, which
applies the given action lazily as the elements are being iterated.
inputDir.walk()
.filter { it.isFile && it.name.endsWith(".txt") }
.onEach { println("Moving $it to $outputDir") }
.forEach { moveFile(it, File(outputDir, it.toRelativeString(inputDir))) }
also(),
takeIf(),
and
takeUnless()
These are three general-purpose extension functions applicable to any receiver.
also is like apply: it takes the receiver, does some action on it, and returns that receiver. The difference is that in the block
inside apply the receiver is available as this, while in the block inside also it's available as it (and you can give it another
name if you want). This comes handy when you do not want to shadow this from the outer scope:
class Block {
lateinit var content: String
}
//sampleStart
fun Block.copy() = Block().also {
it.content = this.content
}
//sampleEnd
157
val copy = block.copy()
println("Testing the content was copied:")
println(block.content == copy.content)
}
takeIf is like filter for a single value. It checks whether the receiver meets the predicate, and returns the receiver, if it does
or null if it doesn't. Combined with an elvis operator (?:) and early returns it allows writing constructs like:
//sampleStart
val index = input.indexOf(keyword).takeIf { it >= 0 } ?: error("keyword not found")
// do something with index of keyword in input string, given that it's found
//sampleEnd
println("'$keyword' was found in '$input'")
println(input)
println(" ".repeat(index) + "^")
}
takeUnless is the same as takeIf, but it takes the inverted predicate. It returns the receiver when it doesn't meet the
predicate and null otherwise. So one of the examples above could be rewritten with takeUnless as following:
It is also convenient to use when you have a callable reference instead of the lambda:
groupingBy()
This API can be used to group a collection by key and fold each group simultaneously. For example, it can be used to
count the number of words starting with each letter:
158
fun main(args: Array<String>) {
val words = "one two three four five six seven eight nine ten".split(' ')
//sampleStart
val frequencies = words.groupingBy { it.first() }.eachCount()
//sampleEnd
println("Counting first letters: $frequencies.")
// The alternative way that uses 'groupBy' and 'mapValues' creates an intermediate map,
// while 'groupingBy' way counts on the fly.
val groupBy = words.groupBy { it.first() }.mapValues { (_, list) -> list.size }
println("Comparing the result with using 'groupBy': ${groupBy == frequencies}.")
}
Map.toMap()
and
Map.toMutableMap()
These functions can be used for easy copying of maps:
Map.minus(key)
The operator plus provides a way to add key-value pair(s) to a read-only map producing a new map, however there was
not a simple way to do the opposite: to remove a key from the map you have to resort to less straightforward ways to like
Map.filter() or Map.filterKeys(). Now the operator minus fills this gap. There are 4 overloads available: for removing a single
key, a collection of keys, a sequence of keys and an array of keys.
minOf()
and
maxOf()
These functions can be used to find the lowest and greatest of two or three given values, where values are primitive
numbers or Comparable objects. There is also an overload of each function that take an additional Comparator instance if
you want to compare objects that are not comparable themselves.
159
val longestList = maxOf(list1, list2, compareBy { it.size })
//sampleEnd
println("minSize = $minSize")
println("longestList = $longestList")
}
Array-like
List
instantiation
functions
Similar to the Array constructor, there are now functions that create List and MutableList instances and initialize each
element by calling a lambda:
println("squares: $squares")
println("mutable: $mutable")
}
Map.getValue()
This extension on Map returns an existing value corresponding to the given key or throws an exception, mentioning which
key was not found. If the map was produced with withDefault, this function will return the default value instead of throwing
an exception.
Abstract
collections
These abstract classes can be used as base classes when implementing Kotlin collection classes. For implementing read-
only collections there are AbstractCollection, AbstractList, AbstractSet and AbstractMap, and for mutable collections
there are AbstractMutableCollection, AbstractMutableList, AbstractMutableSet and AbstractMutableMap. On JVM, these
abstract mutable collections inherit most of their functionality from JDK's abstract collections.
160
Array
manipulation
functions
The standard library now provides a set of functions for element-by-element operations on arrays: comparison
(contentEquals and contentDeepEquals), hash code calculation (contentHashCode and contentDeepHashCode), and
conversion to a string (contentToString and contentDeepToString). They're supported both for the JVM (where they act as
aliases for the corresponding functions in java.util.Arrays) and for JS (where the implementation is provided in the Kotlin
standard library).
JVM
Backend
Java
8
bytecode
support
Kotlin has now the option of generating Java 8 bytecode (-jvm-target 1.8 command line option or the corresponding
options in Ant/Maven/Gradle). For now this doesn't change the semantics of the bytecode (in particular, default methods
in interfaces and lambdas are generated exactly as in Kotlin 1.0), but we plan to make further use of this later.
Java
8
standard
library
support
There are now separate versions of the standard library supporting the new JDK APIs added in Java 7 and 8. If you need
access to the new APIs, use kotlin-stdlib-jre7 and kotlin-stdlib-jre8 maven artifacts instead of the standard kotlin-stdlib.
These artifacts are tiny extensions on top of kotlin-stdlib and they bring it to your project as a transitive dependency.
Parameter
names
in
the
bytecode
Kotlin now supports storing parameter names in the bytecode. This can be enabled using the -java-parameters command
line option.
Constant
inlining
The compiler now inlines values of const val properties into the locations where they are used.
Mutable
closure
variables
The box classes used for capturing mutable closure variables in lambdas no longer have volatile fields. This change
improves performance, but can lead to new race conditions in some rare usage scenarios. If you're affected by this, you
need to provide your own synchronization for accessing the variables.
161
javax.script
support
Kotlin now integrates with the javax.script API (JSR-223). The API allows to evaluate snippets of code at runtime:
kotlin.reflect.full
To prepare for Java 9 support, the extension functions and properties in the kotlin-reflect.jar library have been moved to
the package kotlin.reflect.full. The names in the old package (kotlin.reflect) are deprecated and will be removed in Kotlin
1.2. Note that the core reflection interfaces (such as KClass) are part of the Kotlin standard library, not kotlin-reflect, and
are not affected by the move.
JavaScript
backend
Unified
standard
library
A much larger part of the Kotlin standard library can now be used from code compiled to JavaScript. In particular, key
classes such as collections (ArrayList, HashMap etc.), exceptions (IllegalArgumentException etc.) and a few others
(StringBuilder, Comparator) are now defined under the kotlin package. On the JVM, the names are type aliases for the
corresponding JDK classes, and on the JS, the classes are implemented in the Kotlin standard library.
Better
code
generation
JavaScript backend now generates more statically checkable code, which is friendlier to JS code processing tools, like
minifiers, optimisers, linters, etc.
The
external
modifier
If you need to access a class implemented in JavaScript from Kotlin in a typesafe way, you can write a Kotlin declaration
using the external modifier. (In Kotlin 1.0, the @native annotation was used instead.) Unlike the JVM target, the JS one
permits to use external modifier with classes and properties. For example, here's how you can declare the DOM Node
class:
// etc
}
162
Improved
import
handling
You can now describe declarations which should be imported from JavaScript modules more precisely. If you add the
@JsModule("<module-name>") annotation on an external declaration it will be properly imported to a module system
(either CommonJS or AMD) during the compilation. For example, with CommonJS the declaration will be imported via
require(...) function. Additionally, if you want to import a declaration either as a module or as a global JavaScript object,
you can use the @JsNonModule annotation.
For example, here's how you can import JQuery into a Kotlin module:
@JsModule("jquery")
@JsNonModule
@JsName("$")
external fun jquery(selector: String): JQuery
In this case, JQuery will be imported as a module named jquery. Alternatively, it can be used as a $-object, depending on
what module system Kotlin compiler is configured to use.
What's
new
in
Kotlin
for
KMM
KMM is part of the larger Kotlin ecosystem and leverages Kotlin features and improvements for a better mobile developer
experience. Every Kotlin release brings features and improvements that are helpful for mobile developers like you.
Android Studio will recommend an automatic update to a new Kotlin release. You can also update manually.
Here you can find a short summary of the features Kotlin provides for developing multiplatform mobile applications.
Kotlin
1.5.30
for
KMM
Kotlin 1.5.30 introduces a number of improvements and features that are helpful for KMM:
Apple silicon support. Kotlin 1.5.30 introduces native support for Apple silicon. Now the Kotlin/Native compiler and
163
tooling can run on Apple silicon hardware without Rosetta translation environment
Improved Kotlin DSL for CocoaPods Gradle plugin. Kotlin 1.5.30 introduces the improved CocoaPods Gradle plugin
DSL. In addition to the name of the framework, you can now specify other parameters in the pod configuration:
Bitcode embedding
Experimental interoperability with Swift 5.5 async/await. The Kotlin/Native compiler now emits the _Nullable_result
attribute in the generated Objective-C headers for suspending functions with nullable return types. This makes it
possible to call them from Swift as async functions with the proper nullability.
Improved Swift/Objective-C mapping for objects and companion objects. Getting objects and companion objects can
now be done in a way that is more intuitive for native iOS developers.
Sharing custom cinterop libraries between platforms. Starting from Kotlin 1.5.30, you can use custom cinterop libraries
in shared native code.
Support for XCFrameworks. Now all Kotlin Multiplatform projects can use XCFrameworks.
New default publishing setup for Android artifacts. Kotlin 1.5.30 brings new default publishing setup for Android
artefacts. You can publish your multiplatform library for the Android target by specifying Android variant names in the
build script. The Kotlin Gradle plugin will generate publications automatically.
Learn more about new default publishing setup for Android artifacts.
Kotlin
1.5.20
for
KMM
Kotlin 1.5.20 introduces a number of improvements and features that are helpful for KMM:
Export of KDoc comments to generated Objective-C headers. You can now set the Kotlin/Native compiler to export
the documentation comments (KDoc) from Kotlin code to the Objective-C frameworks generated from it, making them
visible to the frameworks’ consumers.
164
This feature is experimental. We would appreciate your feedback on it in YouTrack.
Learn more about exporting KDoc comments to generated Objective-C headers and how to opt in to this feature.
New framework-packing task for Kotlin/Native. The Kotlin Multiplatform Gradle plugin now includes the
embedAndSignAppleFrameworkForXcode task, which can be used from Xcode to connect KMM modules to the iOS
part of your project.
Check out this blog post to learn about the new framework-packing task and how to remove from the packForXcode
task from your build script.
Kotlin
1.5.0
for
KMM
Kotlin 1.5.0 introduces a number of improvements and features that are helpful for KMM:
Simplified test dependency selection for each platform. Now you can use the kotlin-test dependency to add
dependencies for testing in the commonTest source set. The Gradle plugin will infer the corresponding platform
dependencies for each test source set:
iOS source sets use Kotlin/Native, which has everything built in, so they do not require any additional artifacts.
You can also use the kotlin-test dependency in any shared or platform-specific source set. Learn more about setting
dependencies on test libraries.
New API for getting a char’s Unicode category. A variety of new character-related functions are available on all
platforms and in the common code. They include several functions for checking whether a char is a letter or a digit,
like Char.isLetterOrDigit(), as well as functions for checking the case of a char, like Char.isUpperCase(). The property
Char.category and the enum class CharCategory are available, as well.
Learn more about this new API.
Improved Kotlin/Native performance and stability. Kotlin/Native is receiving a set of performance improvements that
speed up both compilation and execution.
Learn more about the Kotlin/Native improvements.
Kotlin
1.4.30
for
KMM
Kotlin 1.4.30 introduces a number of improvements that are helpful for KMM:
Improved compilation time for an iOS simulator. Recompiling binaries for the iOS simulator after making changes in the
code now requires much less time. You can see the most significant improvements when re-running unit tests or
165
applications on the iOS simulator. For example, the time required to rebuild the framework in the KMM Networking and
data storage sample has decreased from 9.5 seconds (in 1.4.10) to 4.5 seconds (in 1.4.30).
These optimizations affect other scenarios as well.
Support for the new watchosX64 target in Kotlin/Native. This target makes it possible to run the simulator on 64-bit
architecture.
Kotlin
1.4.20
for
KMM
Kotlin 1.4.20 introduces a number of features, improvements, and bug fixes that are helpful for KMM:
Ability to add dependencies on libraries from a custom spec repository, Git repository, or archive, as well as on
libraries with custom cinterop options.
Learn more about adding CocoaPods dependencies and these improvements.
Escape analysis for Kotlin/Native. A prototype of a new mechanism that gives a 10% iOS runtime performance
improvement by allocating certain objects on the stack instead of the heap.
Opt-in wrapping of Objective-C exceptions in runtime to avoid crashes. Learn how to opt in.
Updated structure of multiplatform library publications. The library root publication, which stands for the whole library,
now includes metadata artifacts. These were published separately in earlier Kotlin versions.
For compatibility, both multiplatform library authors and users must update to Kotlin 1.4.20. Learn more about
publishing a multiplatform library.
Deprecation of the Kotlin Android Extensions plugin. The Parcelable implementation generator has been moved to a
separate kotlin-parcelize plugin.
What's
new
in
Kotlin
plugin
2021.2
Enjoy improved performance, a better coroutines debugging experience, WSL 2 and Run Targets support, and more
improvements for Kotlin in IntelliJ IDEA 2021.2:
Performance improvements
166
Remote development support
Performance
improvements
IntelliJ IDEA 2021.2 brings some major performance improvements for Kotlin:
Faster test files analysis. Now you can run tests before code analysis finishes. The Run test icon appears in the gutter
as soon as you open the file and you can run your test immediately.
Run and debug your code before the IDE finishes indexing. The indexing process in the IDE and running code are now
autonomous from each other. You can run or debug the project right away without waiting for the IDE to finish its work.
Improved speed of rename refactoring. Rename refactoring for particular cases, like for fields with common names
name or id, became faster. Check out this YouTrack issue for more details.
Shared indexes for new Spring Boot projects. Shared indexes help you to prevent situations where you open a project
and need to wait for indexing to finish. In the previous version of IntelliJ IDEA you can download the JDK shared
indexes that save time during every project import. Now shared indexes are available for Spring Boot projects. Learn
more about how to download and use shared indexes in the IntelliJ IDEA documentation.
Better
debugging
experience
IntelliJ IDEA 2021.2 brings useful improvements and updates to the coroutine agent in the debugger:
Now you can evaluate suspend function calls during the debugging process. You can put a breakpoint and evaluate
the suspend function:
import kotlinx.coroutines.async
import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking
167
val sum = deferred.await() + fastFun()
println(sum)
}
Look through these YouTrack tickets for more details: KT-27974, KT-31701.
Previously, when local variables were not used after passing a suspension point, you couldn’t see their values in
the Local Variable table. This helped avoid memory leaks, but as a side effect such variables disappeared in the
Variables view of the Debugger tool window.
Now you can see the values of such variables for common cases. IntelliJ IDEA also handles other specific cases
properly and notifies you when it is impossible to obtain the value.
For example, when you debug through the following code, the debugger shows the message that the x1, x2, x3
variables have been optimized out:
import kotlinx.coroutines.runBlocking
}
fun main() = runBlocking {
// Set a breakpoint here:
val x1 = 1
println(x1)
foo()
val x2 = 2
println(x2)
foo()
val x3 = 3
println(x3)
foo()
println()
}
Check out these YouTrack issues for more details: KTIJ-18499, KTIJ-18630.
The coroutines agent is now available for Java, Maven, and Spring run configurations with a dependency on
kotlinx.coroutines.
Remote
development
support
Some popular remote-development scenarios are now available for Kotlin projects: WSL 2 (Windows Subsystem for
Linux) support and the Run Targets feature.
Run, debug, and test your code in different remote environments without leaving the IDE.
168
Kotlin
plugin
in
the
IntelliJ
IDEA
repository
The Kotlin plugin code has been moved to the IntelliJ IDEA repository. That means that every stable IDE release improves
your Kotlin experience and brings you more debugging, refactoring, and IDE-related features. To contribute to the Kotlin
plugin, clone the IntelliJ IDEA repository.
Since the Kotlin plugin and Kotlin have separate release cycles, this creates some limitations that are important to
emphasize:
The EAP version of Kotlin works only with the stable version of the IDE. That means that you can't install the Kotlin EAP
version to the EAP IDEA release.
The Kotlin plugin is based on the previous stable version of the Kotlin compiler. You can still update the Kotlin version
in your project, but some IDE-related features might not be available. We are working on stabilizing the process so that
the next versions of the plugin will be based on the latest stable version of the compiler.
Learn more about the EAP for Kotlin and IntelliJ IDEA.
Other
IDE
improvements
IntelliJ IDEA 2021.2 also brings more IDE features that improve the Kotlin experience:
Automatic ML code completion. Kotlin code completion works based on a machine learning mechanism by default.
Code suggestions are prioritized more carefully as IntelliJ IDEA considers the choices of thousands of real users in
similar situations. You can configure ML-assisted completion in Preferences/Settings | Editor | Code Completion.
Clickable inlay hints. Now you can click the type in the inlay hint and look through the declaration of the type, including
generics types. Just hold Cmd + click the type in the hint:
You can customize the inlay hints’ appearance in Preferences | Editor | Inlay hints | Kotlin.
Package Search integration. Package Search now works with build.gradle.kts files. This feature allows you to upgrade,
downgrade, and remove existing dependencies. You can use it to find new dependencies and add them automatically.
Package Search will add the required repositories to your build script if they’re missing.
169
Advanced settings. There is a new node Advanced Settings in the Preferences | Settings window. It contains some
use-case-specific options conveniently grouped by the IDE tool. For example, you can add a left margin in Distraction-
free mode, or set the maximum number of recent projects which are displayed in the File | Open Recent menu.
Quick access to Eclipse projects. IntelliJ IDEA detects existing Eclipse projects automatically and adds them to the
Welcome screen. To try this feature, select Open existing Eclipse projects on your first IDE launch.
See the What’s new in IntelliJ IDEA 2021.2 blog post to learn more about the platform enhancements.
What's
new
in
Kotlin
plugin
2021.1
This release aims to increase productivity and improve the development experience. Version 2021.1 of the Kotlin plugin
introduces the following major updates:
Performance improvements
You can also learn about new features in this blog post.
Performance
improvements
With 2021.1, the Kotlin plugin has received a number of performance improvements that speed up the development
process.
Faster syntax and error highlighting. The code highlighting API has been reworked, so you now get all the necessary
diagnostic information faster. See the benchmark results and share your feedback in this YouTrack issue.
Code completion speed improvements. The Kotlin plugin provides faster code completion. Check out this YouTrack
issue to see the benchmark results.
This version also introduces other improvements for code completion, particularly code completion for type
arguments.
Improved IDE responsiveness. We’ve fixed numerous issues based on your feedback, and we’ve improved the
overall stability of the plugin, as well as IDE responsiveness.
170
Evaluation
of
custom
getters
during
debugging
This release expands the capabilities of the debugger. One of the most notable features is the ability to display Kotlin
properties without a backing field in the Variables view.
Previously, during a debug session, you could only see the properties without a custom getter and those with a backing
field. Properties with a custom getter didn't appear because they are represented as regular methods on the JVM.
Starting with version 2021.1 of the Kotlin plugin, you can see all such properties and evaluate them on demand by clicking
on `get() near the property name.
For example, when debugging of the following code, you can execute the get() method to see the value:
fun main() {
val version = LanguageVersion(1, 4)
}
In the Debug window, you can see the values of the properties:
Variables view
Improved
Change
Signature
refactoring
This release contains changes to the Change Signature refactoring. We’ve fixed more than 40 issues to make the
refactoring process better.
171
Here are some of the important improvements:
Fixes to inheritance refactoring, including cross-language refactoring. See the YouTrack issue for details.* Improved
UX of properties processing.
Addition of a way to declare the default parameter value. See the YouTrack issue for details.
Code
completion
for
type
arguments
From now on, code completion will offer functions and properties after generic functions and will restore type arguments
where needed. When you select such a function from the list, the IDE adds the correct type argument to the preceding
code.
fun typeArgumentsAtCodeCompletion() {
// Function definition from stdlib:
// public fun <T> emptyList(): List<T>
val list: List<String> = emptyList() // T is inferred from the context (explicit variable
type)
}
To reverse this list, start typing the name of the reversed() function:
After you apply the code completion suggestion, the IDE automatically adds the <String> type:
fun typeArgumentsAtCodeCompletion() {
// Function definition from stdlib:
// public fun <T> emptyList(): List<T>
172
}
The type argument for emptyList() is required to evaluate the expression type. Otherwise, the code will not compile.
UML
diagrams
for
Kotlin
classes
With this release, you can test Kotlin code visualization via UML Class diagrams. To build a diagram, select Diagrams |
Show Diagram... | Kotlin Classes in the Project View.
Currently, the diagrams only show inheritance and nesting relationships. All other more detailed association connections,
like aggregation, composition, dependency, and others will be available in the future releases.
Other
platform
enhancements
Since the plugin and the platform have been moved to the same codebase and now ship simultaneously, this release also
brings the following features that improve the Kotlin experience:
You can now launch the basic memory profiler that was announced in the IntelliJ IDEA 2020.3 release via Gradle run.
173
To improve the experience of working with coroutines, this release provides better thread-blocking call detection. The
inspection now correctly warns you about inappropriate blocking method calls.
We’ve fixed some of the language injection issues that received the most votes. Language injection now works
correctly for the following cases:
When you use triple quotes to inject multi-line strings and add the .trimIndent(), or .trimMargin() functions at the end.
See the YouTrack issue for details.
When you concatenate strings. See the YouTrack issue for details.
What's
new
in
Kotlin
plugin
2020.3
This plugin release introduces the following features:
EditorConfig support
New
types
of
inline
refactorings
Cross-language conversion is possible starting with version 2020.3 of the Kotlin plugin. You can now use the inline
refactoring actions for Kotlin elements defined in Java.
The Kotlin plugin can inline code from libraries with attached sources. That means you can inline refactor all the Kotlin
scope functions: also, let, run, apply, and with.
Also, this release brings refactoring improvements for lambda expressions. Now the IDE analyzes their syntax more
thoroughly and formats them correctly.
Structural
search
and
replace
Structural search and replace (SSR) actions are now available for Kotlin. The SSR feature allows you to find and replace
code patterns, taking the syntax and semantics of the source code into account.
To start using the feature, open the Structural Search dialog for your .kt file and select one of the templates or create your
own.
EditorConfig
support
From 2020.3, the Kotlin API has the full support of .editorconfig files for managing code style on a directory level.
174
Project
templates
for
Jetpack
Compose
for
Desktop
The new experimental Jetpack Compose for Desktop templates are now available in the Kotlin Project Wizard. You can
create a project using the following templates:
Desktop – a Compose project targeting the desktop JVM platform: Windows, Linux, or macOS.
Multiplatform – a Multiplatform Compose project targeting the desktop JVM platform (Windows, Linux, macOS) and
Android with shared code in common modules.
To create a project, select one of the templates while creating a new project and specify the Gradle build system. The
Kotlin plugin creates all the configuration files automatically. You can try out this experimental feature by working through
Getting Started with Compose for Desktop tutorial.
Read more about Jetpack Compose features in this blog post and look through the examples of Compose applications.
Basic
syntax
This is a collection of basic syntax elements with examples. At the end of every section, you'll find a link to a detailed
description of the related topic.
You can also learn all the Kotlin essentials with the free Kotlin Basics track on JetBrains Academy.
175
Package
definition
and
imports
Package specification should be at the top of the source file.
package my.demo
import kotlin.text.*
// ...
It is not required to match directories and packages: source files can be placed arbitrarily in the file system.
See Packages.
Program
entry
point
An entry point of a Kotlin application is the main function.
fun main() {
println("Hello world!")
}
Print
to
the
standard
output
print prints its argument to the standard output.
fun main() {
//sampleStart
print("Hello ")
print("world!")
//sampleEnd
}
println prints its arguments and adds a line break, so that the next thing you print appears on the next line.
fun main() {
//sampleStart
println("Hello world!")
println(42)
//sampleEnd
}
176
Functions
A function with two Int parameters and Int return type.
//sampleStart
fun sum(a: Int, b: Int): Int {
return a + b
}
//sampleEnd
fun main() {
print("sum of 3 and 5 is ")
println(sum(3, 5))
}
//sampleStart
fun sum(a: Int, b: Int) = a + b
//sampleEnd
fun main() {
println("sum of 19 and 23 is ${sum(19, 23)}")
}
//sampleStart
fun printSum(a: Int, b: Int): Unit {
println("sum of $a and $b is ${a + b}")
}
//sampleEnd
fun main() {
printSum(-1, 8)
}
//sampleStart
fun printSum(a: Int, b: Int) {
println("sum of $a and $b is ${a + b}")
}
//sampleEnd
fun main() {
printSum(-1, 8)
}
177
See Functions.
Variables
Read-only local variables are defined using the keyword val. They can be assigned a value only once.
fun main() {
//sampleStart
val a: Int = 1 // immediate assignment
val b = 2 // `Int` type is inferred
val c: Int // Type required when no initializer is provided
c = 3 // deferred assignment
//sampleEnd
println("a = $a, b = $b, c = $c")
}
fun main() {
//sampleStart
var x = 5 // `Int` type is inferred
x += 1
//sampleEnd
println("x = $x")
}
//sampleStart
val PI = 3.14
var x = 0
fun incrementX() {
x += 1
}
//sampleEnd
fun main() {
println("x = $x; PI = $PI")
incrementX()
println("incrementX()")
println("x = $x; PI = $PI")
}
Creating
classes
and
instances
To define a class, use the class keyword.
178
class Shape
The default constructor with parameters listed in the class declaration is available automatically.
Inheritance between classes is declared by a colon (:). Classes are final by default; to make a class inheritable, mark it as
open.
Comments
Just like most modern languages, Kotlin supports single-line (or end-of-line) and multi-line (block) comments.
See Documenting Kotlin Code for information on the documentation comment syntax.
179
String
templates
fun main() {
//sampleStart
var a = 1
// simple name in template:
val s1 = "a is $a"
a = 2
// arbitrary expression in template:
val s2 = "${s1.replace("is", "was")}, but now is $a"
//sampleEnd
println(s2)
}
Conditional
expressions
//sampleStart
fun maxOf(a: Int, b: Int): Int {
if (a > b) {
return a
} else {
return b
}
}
//sampleEnd
fun main() {
println("max of 0 and 42 is ${maxOf(0, 42)}")
}
//sampleStart
fun maxOf(a: Int, b: Int) = if (a > b) a else b
//sampleEnd
fun main() {
println("max of 0 and 42 is ${maxOf(0, 42)}")
}
See if -expressions.
for
loop
fun main() {
//sampleStart
180
val items = listOf("apple", "banana", "kiwifruit")
for (item in items) {
println(item)
}
//sampleEnd
}
or
fun main() {
//sampleStart
val items = listOf("apple", "banana", "kiwifruit")
for (index in items.indices) {
println("item at $index is ${items[index]}")
}
//sampleEnd
}
while
loop
fun main() {
//sampleStart
val items = listOf("apple", "banana", "kiwifruit")
var index = 0
while (index < items.size) {
println("item at $index is ${items[index]}")
index++
}
//sampleEnd
}
when
expression
//sampleStart
fun describe(obj: Any): String =
when (obj) {
1 -> "One"
"Hello" -> "Greeting"
is Long -> "Long"
!is String -> "Not a string"
else -> "Unknown"
}
//sampleEnd
fun main() {
println(describe(1))
println(describe("Hello"))
181
println(describe(1000L))
println(describe(2))
println(describe("other"))
}
Ranges
Check if a number is within a range using in operator.
fun main() {
//sampleStart
val x = 10
val y = 9
if (x in 1..y+1) {
println("fits in range")
}
//sampleEnd
}
fun main() {
//sampleStart
val list = listOf("a", "b", "c")
if (-1 !in 0..list.lastIndex) {
println("-1 is out of range")
}
if (list.size !in list.indices) {
println("list size is out of valid list indices range, too")
}
//sampleEnd
}
fun main() {
//sampleStart
for (x in 1..5) {
print(x)
}
//sampleEnd
}
Or over a progression.
fun main() {
//sampleStart
for (x in 1..10 step 2) {
182
print(x)
}
println()
for (x in 9 downTo 0 step 3) {
print(x)
}
//sampleEnd
}
Collections
Iterate over a collection.
fun main() {
val items = listOf("apple", "banana", "kiwifruit")
//sampleStart
for (item in items) {
println(item)
}
//sampleEnd
}
fun main() {
val items = setOf("apple", "banana", "kiwifruit")
//sampleStart
when {
"orange" in items -> println("juicy")
"apple" in items -> println("apple is fine too")
}
//sampleEnd
}
fun main() {
//sampleStart
val fruits = listOf("banana", "avocado", "apple", "kiwifruit")
fruits
.filter { it.startsWith("a") }
.sortedBy { it }
.map { it.uppercase() }
.forEach { println(it) }
//sampleEnd
}
183
Nullable
values
and
null
checks
A reference must be explicitly marked as nullable when null value is possible. Nullable type names have ? at the end.
//sampleStart
fun printProduct(arg1: String, arg2: String) {
val x = parseInt(arg1)
val y = parseInt(arg2)
fun main() {
printProduct("6", "7")
printProduct("a", "7")
printProduct("a", "b")
}
or
184
println("Wrong number format in arg2: '$arg2'")
return
}
fun main() {
printProduct("6", "7")
printProduct("a", "7")
printProduct("99", "b")
}
See Null-safety.
Type
checks
and
automatic
casts
The is operator checks if an expression is an instance of a type. If an immutable local variable or property is checked for a
specific type, there's no need to cast it explicitly:
//sampleStart
fun getStringLength(obj: Any): Int? {
if (obj is String) {
// `obj` is automatically cast to `String` in this branch
return obj.length
}
fun main() {
fun printLength(obj: Any) {
println("Getting the length of '$obj'. Result: ${getStringLength(obj) ?: "Error: The
object is not a string"} ")
}
printLength("Incomprehensibilities")
printLength(1000)
printLength(listOf(Any()))
}
or
//sampleStart
fun getStringLength(obj: Any): Int? {
if (obj !is String) return null
185
fun main() {
fun printLength(obj: Any) {
println("Getting the length of '$obj'. Result: ${getStringLength(obj) ?: "Error: The
object is not a string"} ")
}
printLength("Incomprehensibilities")
printLength(1000)
printLength(listOf(Any()))
}
or even
//sampleStart
fun getStringLength(obj: Any): Int? {
// `obj` is automatically cast to `String` on the right-hand side of `&&`
if (obj is String && obj.length > 0) {
return obj.length
}
return null
}
//sampleEnd
fun main() {
fun printLength(obj: Any) {
println("Getting the length of '$obj'. Result: ${getStringLength(obj) ?: "Error: The
object is not a string"} ")
}
printLength("Incomprehensibilities")
printLength("")
printLength(1000)
}
Idioms
A collection of random and frequently used idioms in Kotlin. If you have a favorite idiom, contribute it by sending a pull
request.
Create
DTOs
(POJOs/POCOs)
equals()
186
hashCode()
toString()
copy()
Default
values
for
function
parameters
Filter
a
list
Check
the
presence
of
an
element
in
a
collection
String
interpolation
println("Name $name")
Instance
checks
when (x) {
187
is Foo -> ...
is Bar -> ...
else -> ...
}
Read-only
list
Read-only
map
Access
a
map
entry
println(map["key"])
map["key"] = value
Traverse
a
map
or
a
list
of
pairs
Iterate
over
a
range
Lazy
property
188
val p: String by lazy {
// compute the string
}
Extension
functions
Create
a
singleton
object Resource {
val name = "Name"
}
Instantiate
an
abstract
class
fun main() {
val myObject = object : MyAbstractClass() {
override fun doSomething() {
// ...
}
If-not-null
shorthand
189
If-not-null-else
shorthand
Execute
a
statement
if
null
Get
first
item
of
a
possibly
empty
collection
Execute
if
not
null
value?.let {
... // execute this block if not null
}
Map
nullable
value
if
not
null
Return
on
when
statement
190
}
}
try-catch
expression
fun test() {
val result = try {
count()
} catch (e: ArithmeticException) {
throw IllegalStateException(e)
}
if
expression
Builder-style
usage
of
methods
that
return
Unit
Single-expression
functions
fun theAnswer() = 42
This is equivalent to
191
This can be effectively combined with other idioms, leading to shorter code. For example, with the when expression:
Call
multiple
methods
on
an
object
instance
(with)
class Turtle {
fun penDown()
fun penUp()
fun turn(degrees: Double)
fun forward(pixels: Double)
}
Configure
properties
of
an
object
(apply)
This is useful for configuring properties that aren't present in the object constructor.
Java
7's
try-with-resources
192
Generic
function
that
requires
the
generic
type
information
Nullable
Boolean
Swap
two
variables
var a = 1
var b = 2
a = b.also { b = a }
Mark
code
as
incomplete
(TODO)
Kotlin's standard library has a TODO() function that will always throw a NotImplementedError. Its return type is Nothing so
it can be used regardless of expected type. There's also an overload that accepts a reason parameter:
IntelliJ IDEA's kotlin plugin understands the semantics of TODO() and automatically adds a code pointer in the TODO tool
window.
What’s
next?
Learn how to perform typical tasks with strings in Java and Kotlin.
193
Coding
conventions
Commonly known and easy-to-follow coding conventions are vital for any programming language. Here we provide
guidelines on the code style and code organization for projects that use Kotlin.
Configure
style
in
IDE
Two most popular IDEs for Kotlin - IntelliJ IDEA and Android Studio provide powerful support for code styling. You can
configure them to automatically format your code in consistence with the given code style.
Apply
the
style
guide
1. Go to Settings | Editor | Code Style | Kotlin.
Verify
that
your
code
follows
the
style
guide
1. Go to Settings | Editor | Inspections | Kotlin.
3. Switch on File is not formatted according to project settings inspection. Additional inspections that verify other issues
described in the style guide (such as naming conventions) are enabled by default.
Source
code
organization
Directory
structure
In pure Kotlin projects, the recommended directory structure follows the package structure with the common root
package omitted. For example, if all the code in the project is in the org.example.kotlin package and its subpackages, files
with the org.example.kotlin package should be placed directly under the source root, and files in
org.example.kotlin.network.socket should be in the network/socket subdirectory of the source root.
On JVM: In projects where Kotlin is used together with Java, Kotlin source files should reside in the same
source root as the Java source files, and follow the same directory structure: each file should be stored in the
directory corresponding to each package statement.
Source
file
names
194
If a Kotlin file contains a single class (potentially with related top-level declarations), its name should be the same as the
name of the class, with the .kt extension appended. If a file contains multiple classes, or only top-level declarations,
choose a name describing what the file contains, and name the file accordingly. Use upper camel case with an uppercase
first letter (also known as Pascal case), for example, ProcessDeclarations.kt.
The name of the file should describe what the code in the file does. Therefore, you should avoid using meaningless words
such as Util in file names.
Source
file
organization
Placing multiple declarations (classes, top-level functions or properties) in the same Kotlin source file is encouraged as
long as these declarations are closely related to each other semantically, and the file size remains reasonable (not
exceeding a few hundred lines).
In particular, when defining extension functions for a class which are relevant for all clients of this class, put them in the
same file with the class itself. When defining extension functions that make sense only for a specific client, put them next
to the code of that client. Avoid creating files just to hold all extensions of some class.
Class
layout
The contents of a class should go in the following order:
2. Secondary constructors
3. Method declarations
4. Companion object
Do not sort the method declarations alphabetically or by visibility, and do not separate regular methods from extension
methods. Instead, put related stuff together, so that someone reading the class from top to bottom can follow the logic of
what's happening. Choose an order (either higher-level stuff first, or vice versa) and stick to it.
Put nested classes next to the code that uses those classes. If the classes are intended to be used externally and aren't
referenced inside the class, put them in the end, after the companion object.
Interface
implementation
layout
When implementing an interface, keep the implementing members in the same order as members of the interface (if
necessary, interspersed with additional private methods used for the implementation).
Overload
layout
Always put overloads next to each other in a class.
Naming
rules
195
Package and class naming rules in Kotlin are quite simple:
Names of packages are always lowercase and do not use underscores (org.example.project). Using multi-word names
is generally discouraged, but if you do need to use multiple words, you can either just concatenate them together or
use camel case (org.example.myProject).
Names of classes and objects start with an uppercase letter and use camel case:
Function
names
Names of functions, properties and local variables start with a lowercase letter and use camel case and no underscores:
Exception: factory functions used to create instances of classes can have the same name as the abstract return type:
Names
for
test
methods
In tests (and only in tests), you can use method names with spaces enclosed in backticks. Note that such method names
are currently not supported by the Android runtime. Underscores in method names are also allowed in test code.
class MyTestCase {
@Test fun `ensure everything works`() { /*...*/ }
@Test fun ensureEverythingWorks_onAndroid() { /*...*/ }
}
Property
names
Names of constants (properties marked with const, or top-level or object val properties with no custom get function that
hold deeply immutable data) should use uppercase underscore-separated (screaming snake case) names:
196
Names of top-level or object properties which hold objects with behavior or mutable data should use camel case names:
Names of properties holding references to singleton objects can use the same naming style as object declarations:
For enum constants, it's OK to use either uppercase underscore-separated names ( screaming snake case) (enum class
Color { RED, GREEN }) or upper camel case names, depending on the usage.
Names
for
backing
properties
If a class has two properties which are conceptually the same but one is part of a public API and another is an
implementation detail, use an underscore as the prefix for the name of the private property:
class C {
private val _elementList = mutableListOf<Element>()
Choose
good
names
The name of a class is usually a noun or a noun phrase explaining what the class is: List, PersonReader.
The name of a method is usually a verb or a verb phrase saying what the method does: close, readPersons. The name
should also suggest if the method is mutating the object or returning a new one. For instance sort is sorting a collection in
place, while sorted is returning a sorted copy of the collection.
The names should make it clear what the purpose of the entity is, so it's best to avoid using meaningless words
(Manager, Wrapper) in names.
When using an acronym as part of a declaration name, capitalize it if it consists of two letters ( IOStream); capitalize only
the first letter if it is longer (XmlFormatter, HttpInputStream).
Formatting
Indentation
Use four spaces for indentation. Do not use tabs.
For curly braces, put the opening brace in the end of the line where the construct begins, and the closing brace on a
separate line aligned horizontally with the opening construct.
197
if (elements != null) {
for (element in elements) {
// ...
}
}
In Kotlin, semicolons are optional, and therefore line breaks are significant. The language design assumes Java-
style braces, and you may encounter surprising behavior if you try to use a different formatting style.
Horizontal
whitespace
Put spaces around binary operators (a + b). Exception: don't put spaces around the "range to" operator (0..i).
Put spaces between control flow keywords (if, when, for, and while) and the corresponding opening parenthesis.
Do not put a space before an opening parenthesis in a primary constructor declaration, method declaration or method
call.
fun bar() {
foo(1)
}
Do not put spaces around angle brackets used to specify type parameters: class Map<K, V> { ... }
As a general rule, avoid horizontal alignment of any kind. Renaming an identifier to a name with a different length should
not affect the formatting of either the declaration or any of the usages.
Colon
Put a space before : in the following cases:
198
when delegating to a superclass constructor or a different constructor of the same class
Don't put a space before : when it separates a declaration and its type.
Class
headers
Classes with a few primary constructor parameters can be written in a single line:
Classes with longer headers should be formatted so that each primary constructor parameter is in a separate line with
indentation. Also, the closing parenthesis should be on a new line. If you use inheritance, the superclass constructor call
or the list of implemented interfaces should be located on the same line as the parenthesis:
class Person(
id: Int,
name: String,
surname: String
) : Human(id, name) { /*...*/ }
For multiple interfaces, the superclass constructor call should be located first and then each interface should be located
in a different line:
class Person(
id: Int,
name: String,
surname: String
) : Human(id, name),
KotlinMaker { /*...*/ }
For classes with a long supertype list, put a line break after the colon and align all supertype names horizontally:
class MyFavouriteVeryLongClassHolder :
MyLongHolder<MyFavouriteVeryLongClass>(),
SomeOtherInterface,
AndAnotherOne {
199
fun foo() { /*...*/ }
}
To clearly separate the class header and body when the class header is long, either put a blank line following the class
header (as in the example above), or put the opening curly brace on a separate line:
class MyFavouriteVeryLongClassHolder :
MyLongHolder<MyFavouriteVeryLongClass>(),
SomeOtherInterface,
AndAnotherOne
{
fun foo() { /*...*/ }
}
Use regular indent (four spaces) for constructor parameters. This ensures that properties declared in the primary
constructor have the same indentation as properties declared in the body of a class.
Modifiers
order
If a declaration has multiple modifiers, always put them in the following order:
@Named("Foo")
private val foo: Foo
Unless you're working on a library, omit redundant modifiers (for example, public).
Annotations
Place annotations on separate lines before the declaration to which they are attached, and with the same indentation:
200
@Target(AnnotationTarget.PROPERTY)
annotation class JsonExclude
@JsonExclude @JvmField
var x: String
A single annotation without arguments may be placed on the same line as the corresponding declaration:
File
annotations
File annotations are placed after the file comment (if any), before the package statement, and are separated from package
with a blank line (to emphasize the fact that they target the file and not the package).
package foo.bar
Functions
If the function signature doesn't fit on a single line, use the following syntax:
fun longMethodName(
argument: ArgumentType = defaultValue,
argument2: AnotherArgumentType,
): ReturnType {
// body
}
Use regular indent (four spaces) for function parameters. It helps ensure consistency with constructor parameters.
Prefer using an expression body for functions with the body consisting of a single expression.
Expression
bodies
If the function has an expression body whose first line doesn't fit on the same line as the declaration, put the = sign on the
201
first line and indent the expression body by four spaces.
Properties
For very simple read-only properties, consider one-line formatting:
For more complex properties, always put get and set keywords on separate lines:
For properties with an initializer, if the initializer is long, add a line break after the = sign and indent the initializer by four
spaces:
Control
flow
statements
If the condition of an if or when statement is multiline, always use curly braces around the body of the statement. Indent
each subsequent line of the condition by four spaces relative to statement begin. Put the closing parentheses of the
condition together with the opening curly brace on a separate line:
if (!component.isSyncing &&
!hasAnyKotlinRuntimeInScope(module)
) {
return createKotlinNotConfiguredPanel(module)
}
Put the else, catch, finally keywords, as well as the while keyword of a do-while loop, on the same line as the preceding
curly brace:
if (condition) {
// body
} else {
// else part
}
try {
// body
202
} finally {
// cleanup
}
In a when statement, if a branch is more than a single line, consider separating it from adjacent case blocks with a blank
line:
Put short branches on the same line as the condition, without braces.
when (foo) {
true -> bar() // good
false -> { baz() } // bad
}
Method
calls
In long argument lists, put a line break after the opening parenthesis. Indent arguments by four spaces. Group multiple
closely related arguments on the same line.
drawSquare(
x = 10, y = 10,
width = 100, height = 100,
fill = true
)
Put spaces around the = sign separating the argument name and value.
Wrap
chained
calls
When wrapping chained calls, put the . character or the ?. operator on the next line, with a single indent:
The first call in the chain usually should have a line break before it, but it's OK to omit it if the code makes more sense that
way.
203
Lambdas
In lambda expressions, spaces should be used around the curly braces, as well as around the arrow which separates the
parameters from the body. If a call takes a single lambda, pass it outside of parentheses whenever possible.
list.filter { it > 10 }
If assigning a label for a lambda, do not put a space between the label and the opening curly brace:
fun foo() {
ints.forEach lit@{
// ...
}
}
When declaring parameter names in a multiline lambda, put the names on the first line, followed by the arrow and the
newline:
If the parameter list is too long to fit on a line, put the arrow on a separate line:
foo {
context: Context,
environment: Env
->
context.configureEnv(environment)
}
Trailing
commas
A trailing comma is a comma symbol after the last item of a series of elements:
class Person(
val firstName: String,
val lastName: String,
val age: Int, // trailing comma
)
It makes version-control diffs cleaner – as all the focus is on the changed value.
It makes it easy to add and reorder elements – there is no need to add or delete the comma if you manipulate
elements.
It simplifies code generation, for example, for object initializers. The last element can also have a comma.
204
Trailing commas are entirely optional – your code will still work without them. The Kotlin style guide encourages the use
of trailing commas at the declaration site and leaves it at your discretion for the call site.
To enable trailing commas in the IntelliJ IDEA formatter, go to Settings | Editor | Code Style | Kotlin, open the Other tab
and select the Use trailing comma option.
Enumerations
Value arguments
class Customer(
val name: String,
val lastName: String, // trailing comma
)
class Customer(
val name: String,
lastName: String, // trailing comma
)
fun powerOf(
number: Int,
exponent: Int, // trailing comma
) { /*...*/ }
constructor(
x: Comparable<Number>,
y: Iterable<Number>, // trailing comma
205
) {}
fun print(
vararg quantity: Int,
description: String, // trailing comma
) {}
Indexing suffix
class Surface {
operator fun get(x: Int, y: Int) = 2 * x + 4 * y - 10
}
fun getZValue(mySurface: Surface, xValue: Int, yValue: Int) =
mySurface[
xValue,
yValue, // trailing comma
]
Parameters in lambdas
fun main() {
val x = {
x: Comparable<Number>,
y: Iterable<Number>, // trailing comma
->
println("1")
}
println(x)
}
when entry
206
}
Type arguments
Type parameters
class MyMap<
MyKey,
MyValue, // trailing comma
> {}
Destructuring declarations
data class Car(val manufacturer: String, val model: String, val year: Int)
val myCar = Car("Tesla", "Y", 2019)
val (
manufacturer,
model,
year, // trailing comma
) = myCar
val cars = listOf<Car>()
fun printMeanValue() {
var meanValue: Int = 0
for ((
_,
_,
year, // trailing comma
) in cars) {
meanValue += year
207
}
println(meanValue/cars.size)
}
printMeanValue()
Documentation
comments
For longer documentation comments, place the opening /** on a separate line and begin each subsequent line with an
asterisk:
/**
* This is a documentation comment
* on multiple lines.
*/
Generally, avoid using @param and @return tags. Instead, incorporate the description of parameters and return values
directly into the documentation comment, and add links to parameters wherever they are mentioned. Use @param and
@return only when a lengthy description is required which doesn't fit into the flow of the main text.
/**
* Returns the absolute value of the given number.
* @param number The number to return the absolute value for.
* @return The absolute value.
*/
fun abs(number: Int) { /*...*/ }
// Do this instead:
/**
* Returns the absolute value of the given [number].
*/
fun abs(number: Int) { /*...*/ }
Avoid
redundant
constructs
In general, if a certain syntactic construction in Kotlin is optional and highlighted by the IDE as redundant, you should omit
it in your code. Do not leave unnecessary syntactic elements in code just "for clarity".
Unit
return
type
If a function returns Unit, the return type should be omitted:
208
fun foo() { // ": Unit" is omitted here
Semicolons
Omit semicolons whenever possible.
String
templates
Don't use curly braces when inserting a simple variable into a string template. Use curly braces only for longer
expressions.
Idiomatic
use
of
language
features
Immutability
Prefer using immutable data to mutable. Always declare local variables and properties as val rather than var if they are not
modified after initialization.
Always use immutable collection interfaces (Collection, List, Set, Map) to declare collections which are not mutated.
When using factory functions to create collection instances, always use functions that return immutable collection types
when possible:
// Bad: use of mutable collection type for value which will not be mutated
fun validateValue(actualValue: String, allowedValues: HashSet<String>) { ... }
Default
parameter
values
Prefer declaring functions with default parameter values to declaring overloaded functions.
// Bad
fun foo() = foo("a")
fun foo(a: String) { /*...*/ }
209
// Good
fun foo(a: String = "a") { /*...*/ }
Type
aliases
If you have a functional type or a type with type parameters which is used multiple times in a codebase, prefer defining a
type alias for it:
If you use a private or internal type alias for avoiding name collision, prefer the import … as … mentioned in Packages
and Imports.
Lambda
parameters
In lambdas which are short and not nested, it's recommended to use the it convention instead of declaring the parameter
explicitly. In nested lambdas with parameters, always declare parameters explicitly.
Returns
in
a
lambda
Avoid using multiple labeled returns in a lambda. Consider restructuring the lambda so that it will have a single exit point.
If that's not possible or not clear enough, consider converting the lambda into an anonymous function.
Named
arguments
Use the named argument syntax when a method takes multiple parameters of the same primitive type, or for parameters
of Boolean type, unless the meaning of all parameters is absolutely clear from context.
Conditional
statements
Prefer using the expression form of try, if, and when.
return when(x) {
0 -> "zero"
else -> "nonzero"
}
210
if (x)
return foo()
else
return bar()
when(x) {
0 -> return "zero"
else -> return "nonzero"
}
if
versus
when
Prefer using if for binary conditions instead of when. For example, use this syntax with if:
when (x) {
null -> // ...
else -> // ...
}
Nullable
Boolean
values
in
conditions
If you need to use a nullable Boolean in a conditional statement, use if (value == true) or if (value == false) checks.
Loops
Prefer using higher-order functions (filter, map etc.) to loops. Exception: forEach (prefer using a regular for loop instead,
unless the receiver of forEach is nullable or forEach is used as part of a longer call chain).
When making a choice between a complex expression using multiple higher-order functions and a loop, understand the
cost of the operations being performed in each case and keep performance considerations in mind.
Loops
on
ranges
Use the until function to loop over an open range:
211
Strings
Prefer string templates to string concatenation.
Prefer multiline strings to embedding \n escape sequences into regular string literals.
To maintain indentation in multiline strings, use trimIndent when the resulting string does not require any internal
indentation, or trimMargin when internal indentation is required:
fun main() {
//sampleStart
println("""
Not
trimmed
text
"""
)
println("""
Trimmed
text
""".trimIndent()
)
println()
println(a)
//sampleEnd
}
Functions
vs
properties
In some cases functions with no arguments might be interchangeable with read-only properties. Although the semantics
are similar, there are some stylistic conventions on when to prefer one to another.
returns the same result over invocations if the object state hasn't changed
Extension
functions
Use extension functions liberally. Every time you have a function that works primarily on an object, consider making it an
extension function accepting that object as a receiver. To minimize API pollution, restrict the visibility of extension
212
functions as much as it makes sense. As necessary, use local extension functions, member extension functions, or top-
level extension functions with private visibility.
Infix
functions
Declare a function as infix only when it works on two objects which play a similar role. Good examples: and, to, zip. Bad
example: add.
Factory
functions
If you declare a factory function for a class, avoid giving it the same name as the class itself. Prefer using a distinct name
making it clear why the behavior of the factory function is special. Only if there is really no special semantics, you can use
the same name as the class.
If you have an object with multiple overloaded constructors that don't call different superclass constructors and can't be
reduced to a single constructor with default argument values, prefer to replace the overloaded constructors with factory
functions.
Platform
types
A public function/method returning an expression of a platform type must declare its Kotlin type explicitly:
Any property (package-level or class-level) initialized with an expression of a platform type must declare its Kotlin type
explicitly:
class Person {
val name: String = MyJavaApi.getProperty("name")
}
A local value initialized with an expression of a platform type may or may not have a type declaration:
fun main() {
val name = MyJavaApi.getProperty("name")
println(name)
}
213
Scope
functions
apply/with/run/also/let
Kotlin provides a set of functions to execute a block of code in the context of a given object: let, run, with, apply, and
also. For the guidance on choosing the right scope function for your case, refer to Scope Functions.
Coding
conventions
for
libraries
When writing libraries, it's recommended to follow an additional set of rules to ensure API stability:
Always explicitly specify member visibility (to avoid accidentally exposing declarations as public API)
Always explicitly specify function return types and property types (to avoid accidentally changing the return type when
the implementation changes)
Provide KDoc comments for all public members, with the exception of overrides that do not require any new
documentation (to support generating documentation for the library)
Basic
types
In Kotlin, everything is an object in the sense that we can call member functions and properties on any variable. Some
types can have a special internal representation - for example, numbers, characters and booleans can be represented as
primitive values at runtime - but to the user they look like ordinary classes. In this section we describe the basic types
used in Kotlin: numbers, booleans, characters, strings, and arrays.
Numbers
Integer
types
Kotlin provides a set of built-in types that represent numbers.
For integer numbers, there are four types with different sizes and, hence, value ranges.
All variables initialized with integer values not exceeding the maximum value of Int have the inferred type Int. If the initial
value exceeds this value, then the type is Long. To specify the Long value explicitly, append the suffix L to the value.
214
val one = 1 // Int
val threeBillion = 3000000000 // Long
val oneLong = 1L // Long
val oneByte: Byte = 1
Floating-point
types
For real numbers, Kotlin provides floating-point types Float and Double. According to the IEEE 754 standard, floating
point types differ by their decimal place, that is, how many decimal digits they can store. Float reflects the IEEE 754 single
precision, while Double provides double precision.
Float 32 24 8 6-7
Double 64 53 11 15-16
You can initialize Double and Float variables with numbers having a fractional part. It's separated from the integer part by
a period (.) For variables initialized with fractional numbers, the compiler infers the Double type.
To explicitly specify the Float type for a value, add the suffix f or F. If such a value contains more than 6-7 decimal digits,
it will be rounded.
Note that unlike some other languages, there are no implicit widening conversions for numbers in Kotlin. For example, a
function with a Double parameter can be called only on Double values, but not Float, Int, or other numeric values.
fun main() {
fun printDouble(d: Double) { print(d) }
val i = 1
val d = 1.0
val f = 1.0f
printDouble(d)
// printDouble(i) // Error: Type mismatch
// printDouble(f) // Error: Type mismatch
}
215
Literal
constants
There are the following kinds of literal constants for integral values:
Decimals: 123
Longs are tagged by a capital L: 123L
Hexadecimals: 0x0F
Binaries: 0b00001011
Numbers
representation
on
the
JVM
On the JVM platform, numbers are stored as primitive types: int, double, and so on. Exceptions are cases when you
create a nullable number reference such as Int? or use generics. In these cases numbers are boxed in Java classes
Integer, Double, and so on.
Note that nullable references to the same number can be different objects:
fun main() {
//sampleStart
val a: Int = 100
val boxedA: Int? = a
val anotherBoxedA: Int? = a
val b: Int = 10000
val boxedB: Int? = b
val anotherBoxedB: Int? = b
println(boxedA === anotherBoxedA) // true
println(boxedB === anotherBoxedB) // false
//sampleEnd
}
216
All nullable references to a are actually the same object because of the memory optimization that JVM applies to Integer s
between -128 and 127. It doesn't apply to the b references, so they are different objects.
fun main() {
//sampleStart
val b: Int = 10000
println(b == b) // Prints 'true'
val boxedB: Int? = b
val anotherBoxedB: Int? = b
println(boxedB == anotherBoxedB) // Prints 'true'
//sampleEnd
}
Explicit
conversions
Due to different representations, smaller types are not subtypes of bigger ones. If they were, we would have troubles of
the following sort:
As a consequence, smaller types are NOT implicitly converted to bigger types. This means that assigning a value of type
Byte to an Int variable requires an explicit conversion.
fun main() {
//sampleStart
val b: Byte = 1 // OK, literals are checked statically
// val i: Int = b // ERROR
val i1: Int = b.toInt()
//sampleEnd
}
toByte(): Byte
toShort(): Short
toInt(): Int
toLong(): Long
toFloat(): Float
217
toDouble(): Double
toChar(): Char
In many cases, there is no need in explicit conversions because the type is inferred from the context, and arithmetical
operations are overloaded for appropriate conversions, for example:
Operations
Kotlin supports the standard set of arithmetical operations over numbers: +, -, *, /, %. They are declared as members of
appropriate classes.
fun main() {
//sampleStart
println(1 + 2)
println(2_500_000_000L - 1L)
println(3.14 * 2.71)
println(10.0 / 3)
//sampleEnd
}
You can also override these operators for custom classes. See Operator overloading for details.
Division of integers
Division between integers numbers always returns an integer number. Any fractional part is discarded.
fun main() {
//sampleStart
val x = 5 / 2
//println(x == 2.5) // ERROR: Operator '==' cannot be applied to 'Int' and 'Double'
println(x == 2)
//sampleEnd
}
fun main() {
//sampleStart
val x = 5L / 2
println(x == 2L)
//sampleEnd
}
To return a floating-point type, explicitly convert one of the arguments to a floating-point type.
fun main() {
218
//sampleStart
val x = 5 / 2.toDouble()
println(x == 2.5)
//sampleEnd
}
Bitwise operations
Kotlin provides a set of bitwise operations on integer numbers. They operate on the binary level directly with bits of the
numbers' representation. Bitwise operations are represented by functions that can be called in infix form. They can be
applied only to Int and Long.
Floating-point
numbers
comparison
The operations on floating-point numbers discussed in this section are:
When the operands a and b are statically known to be Float or Double or their nullable counterparts (the type is declared
or inferred or is a result of a smart cast), the operations on the numbers and the range that they form follow the IEEE 754
Standard for Floating-Point Arithmetic.
However, to support generic use cases and provide total ordering, when the operands are not statically typed as floating
point numbers (e.g. Any, Comparable<...>, a type parameter), the operations use the equals and compareTo
implementations for Float and Double, which disagree with the standard, so that:
219
-0.0 is considered less than 0.0
Unsigned
integers
In addition to integer types, Kotlin provides the following types for unsigned integer numbers:
Changing type from unsigned type to signed counterpart (and vice versa) is a binary incompatible change.
Unsigned arrays and operations on them are in Beta. They can be changed incompatibly at any time. Opt-in is
required (see the details below).
Same as for primitives, each of unsigned type has corresponding type that represents arrays of that type:
Same as for signed integer arrays, they provide similar API to Array class without boxing overhead.
When you use unsigned arrays, you'll get a warning that indicates that this feature is not stable yet. To remove the
warning, opt in using the @ExperimentalUnsignedTypes annotation. It's up to you to decide if your clients have to
explicitly opt-in into usage of your API, but keep in mind that unsigned array are not a stable feature, so API which uses
them can be broken by changes in the language. Learn more about opt-in requirements.
Ranges and progressions are supported for UInt and ULong by classes UIntRange, UIntProgression, ULongRange, and
ULongProgression. Together with the unsigned integer types, these classes are stable.
Literals
To make unsigned integers easier to use, Kotlin provides an ability to tag an integer literal with a suffix indicating a
220
specific unsigned type (similarly to Float or Long):
u and U tag unsigned literals. The exact type is determined based on the expected type. If no expected type is
provided, compiler will use UInt or ULong depending on the size of literal.
val a = 1UL // ULong, even though no expected type provided and constant fits into UInt
Further discussion
See language proposal for unsigned types for technical details and further discussion.
Booleans
The type Boolean represents boolean objects that can have two values: true and false.
Boolean has a nullable counterpart Boolean? that also has the null value.
fun main() {
//sampleStart
val myTrue: Boolean = true
val myFalse: Boolean = false
val boolNull: Boolean? = null
println(myTrue || myFalse)
println(myTrue && myFalse)
println(!myTrue)
//sampleEnd
}
221
On JVM: nullable references to boolean objects are boxed similarly to numbers.
Characters
Characters are represented by the type Char. Character literals go in single quotes: '1'.
Special characters start from an escaping backslash \. The following escape sequences are supported: \t, \b, \n, \r, \', \",
\\ and \$.
To encode any other character, use the Unicode escape sequence syntax: '\uFF00'.
fun main() {
//sampleStart
val aChar: Char = 'a'
println(aChar)
println('\n') //prints an extra newline character
println('\uFF00')
//sampleEnd
}
If a value of character variable is a digit, you can explicitly convert it to an Int number using the digitToInt() function.
On JVM: Like numbers, characters are boxed when a nullable reference is needed. Identity is not preserved by
the boxing operation.
Strings
Strings in Kotlin are represented by the type String. Generally, a string value is a sequence of characters in double quotes
(").
Elements of a string are characters that you can access via the indexing operation: s[i]. You can iterate over these
characters with a for loop:
fun main() {
val str = "abcd"
//sampleStart
for (c in str) {
println(c)
}
//sampleEnd
}
222
Strings are immutable. Once you initialize a string, you can't change its value or assign a new value to it. All operations
that transform strings return their results in a new String object, leaving the original string unchanged.
fun main() {
//sampleStart
val str = "abcd"
println(str.uppercase()) // Create and print a new String object
println(str) // the original string remains the same
//sampleEnd
}
To concatenate strings, use the + operator. This also works for concatenating strings with values of other types, as long
as the first element in the expression is a string:
fun main() {
//sampleStart
val s = "abc" + 1
println(s + "def")
//sampleEnd
}
Note that in most cases using string templates or raw strings is preferable to string concatenation.
String
literals
Kotlin has two types of string literals:
Escaping is done in the conventional way, with a backslash (\). See Characters above for the list of supported escape
sequences.
A raw string is delimited by a triple quote ("""), contains no escaping and can contain newlines and any other characters:
To remove leading whitespace from raw strings, use the trimMargin() function:
223
|Teach me and I remember.
|Involve me and I learn.
|(Benjamin Franklin)
""".trimMargin()
By default, | is used as margin prefix, but you can choose another character and pass it as a parameter, like
trimMargin(">").
String
templates
String literals may contain template expressions - pieces of code that are evaluated and whose results are concatenated
into the string. A template expression starts with a dollar sign ($) and consists of either a name:
fun main() {
//sampleStart
val i = 10
println("i = $i") // prints "i = 10"
//sampleEnd
}
fun main() {
//sampleStart
val s = "abc"
println("$s.length is ${s.length}") // prints "abc.length is 3"
//sampleEnd
}
You can use templates both in raw and escaped strings. To insert the $ character in a raw string (which doesn't support
backslash escaping) before any symbol, which is allowed as a beginning of an identifier, use the following syntax:
Arrays
Arrays in Kotlin are represented by the Array class. It has get and set functions that turn into [] by operator overloading
conventions, and the size property, along with other useful member functions:
224
}
To create an array, use the function arrayOf() and pass the item values to it, so that arrayOf(1, 2, 3) creates an array [1, 2,
3]. Alternatively, the arrayOfNulls() function can be used to create an array of a given size filled with null elements.
Another option is to use the Array constructor that takes the array size and the function that returns values of array
elements given its index:
fun main() {
//sampleStart
// Creates an Array<String> with values ["0", "1", "4", "9", "16"]
val asc = Array(5) { i -> (i * i).toString() }
asc.forEach { println(it) }
//sampleEnd
}
As we said above, the [] operation stands for calls to member functions get() and set().
Arrays in Kotlin are invariant. This means that Kotlin does not let us assign an Array<String> to an Array<Any>, which
prevents a possible runtime failure (but you can use Array<out Any>, see Type Projections).
Primitive
type
arrays
Kotlin also has classes that represent arrays of primitive types without boxing overhead: ByteArray, ShortArray, IntArray,
and so on. These classes have no inheritance relation to the Array class, but they have the same set of methods and
properties. Each of them also has a corresponding factory function:
Type
checks
and
casts
is
and
!is
operators
Use the is operator or its negated form !is to perform a runtime check that identifies whether an object conforms to a
225
given type:
if (obj is String) {
print(obj.length)
}
Smart
casts
In most cases, you don't need to use explicit cast operators in Kotlin because the compiler tracks the is -checks and
explicit casts for immutable values and inserts (safe) casts automatically when necessary:
The compiler is smart enough to know that a cast is safe if a negative check leads to a return:
Smart casts work for when expressions and while loops as well:
when (x) {
is Int -> print(x + 1)
is String -> print(x.length + 1)
is IntArray -> print(x.sum())
}
Note that smart casts work only when the compiler can guarantee that the variable won't change between the check and
the usage. More specifically, smart casts can be used under the following conditions:
226
val local variables - always, with the exception of local delegated properties.
val properties - if the property is private or internal or if the check is performed in the same module where the property
is declared. Smart casts cannot be used on open properties or properties that have custom getters.
var local variables - if the variable is not modified between the check and the usage, is not captured in a lambda that
modifies it, and is not a local delegated property.
var properties - never, because the variable can be modified at any time by other code.
"Unsafe"
cast
operator
Usually, the cast operator throws an exception if the cast isn't possible. And so, it's called unsafe. The unsafe cast in
Kotlin is done by the infix operator as.
Note that null cannot be cast to String, as this type is not nullable. If y is null, the code above throws an exception. To
make code like this correct for null values, use the nullable type on the right-hand side of the cast:
"Safe"
(nullable)
cast
operator
To avoid exceptions, use the safe cast operator as?, which returns null on failure.
Note that despite the fact that the right-hand side of as? is a non-null type String, the result of the cast is nullable.
Type
erasure
and
generic
type
checks
Kotlin ensures type safety for operations involving generics at compile time, while, at runtime, instances of generic types
don't hold information about their actual type arguments. For example, List<Foo> is erased to just List<*>. In general,
there is no way to check whether an instance belongs to a generic type with certain type arguments at runtime.
Because of that, the compiler prohibits is -checks that cannot be performed at runtime due to type erasure, such as ints
is List<Int> or list is T (type parameter). You can, however, check an instance against a star-projected type:
if (something is List<*>) {
something.forEach { println(it) } // The items are typed as `Any?`
}
227
Similarly, when you already have the type arguments of an instance checked statically (at compile time), you can make an
is -check or a cast that involves the non-generic part of the type. Note that angle brackets are omitted in this case:
The same syntax but with the type arguments omitted can be used for casts that do not take type arguments into
account: list as ArrayList.
Inline functions with reified type parameters have their actual type arguments inlined at each call site. This enables arg is T
checks for the type parameters, but if arg is an instance of a generic type itself, its type arguments are still erased.
//sampleStart
inline fun <reified A, reified B> Pair<*, *>.asPairOf(): Pair<A, B>? {
if (first !is A || second !is B) return null
return first as A to second as B
}
//sampleEnd
fun main() {
println("stringToSomething = " + stringToSomething)
println("stringToInt = " + stringToInt)
println("stringToList = " + stringToList)
println("stringToStringList = " + stringToStringList)
//println(stringToStringList?.second?.forEach() {it.length}) // This will throw
ClassCastException as list items are not String
}
Unchecked
casts
As established above, type erasure makes checking the actual type arguments of a generic type instance impossible at
runtime. Additionally, generic types in the code might not be connected to each other closely enough for the compiler to
ensure type safety.
Even so, sometimes we have high-level program logic that implies type safety instead. For example:
228
fun readDictionary(file: File): Map<String, *> = file.inputStream().use {
TODO("Read a mapping of strings to arbitrary elements.")
}
A warning appears for the cast in the last line. The compiler can't fully check it at runtime and provides no guarantee that
the values in the map are Int.
To avoid unchecked casts, you can redesign the program structure. In the example above, you could use the
DictionaryReader<T> and DictionaryWriter<T> interfaces with type-safe implementations for different types. You can
introduce reasonable abstractions to move unchecked casts from the call site to the implementation details. Proper use of
generic variance can also help.
For generic functions, using reified type parameters makes casts like arg as T checked, unless arg 's type has its own
type arguments that are erased.
An unchecked cast warning can be suppressed by annotating the statement or the declaration where it occurs with
@Suppress("UNCHECKED_CAST"):
On the JVM: array types (Array<Foo>) retain information about the erased type of their elements, and type casts
to an array type are partially checked: the nullability and actual type arguments of the element type are still
erased. For example, the cast foo as Array<List<String>?> will succeed if foo is an array holding any List<*>,
whether it is nullable or not.
Conditions
and
loops
If
expression
In Kotlin, if is an expression: it returns a value. Therefore, there is no ternary operator (condition ? then : else) because
ordinary if works fine in this role.
var max = a
if (a < b) max = b
229
// With else
var max: Int
if (a > b) {
max = a
} else {
max = b
}
// As expression
val max = if (a > b) a else b
Branches of if branches can be blocks. In this case, the last expression is the value of a block:
If you're using if as an expression, for example, for returning its value or assigning it to a variable, the else branch is
mandatory.
When
expression
when defines a conditional expression with multiple branches. It is similar to the switch statement in C-like languages. Its
simple form looks like this.
when (x) {
1 -> print("x == 1")
2 -> print("x == 2")
else -> {
print("x is neither 1 nor 2")
}
}
when matches its argument against all branches sequentially until some branch condition is satisfied.
when can be used either as an expression or as a statement. If it is used as an expression, the value of the first matching
branch becomes the value of the overall expression. If it is used as a statement, the values of individual branches are
ignored. Just like with if, each branch can be a block, and its value is the value of the last expression in the block.
The else branch is evaluated if none of the other branch conditions are satisfied. If when is used as an expression, the
else branch is mandatory, unless the compiler can prove that all possible cases are covered with branch conditions, for
example, with enum class entries and sealed class subtypes).
230
}
To define a common behavior for multiple cases, combine their conditions in a single line with a comma:
when (x) {
0, 1 -> print("x == 0 or x == 1")
else -> print("otherwise")
}
You can use arbitrary expressions (not only constants) as branch conditions
when (x) {
s.toInt() -> print("s encodes x")
else -> print("s does not encode x")
}
You can also check a value for being in or !in a range or a collection:
when (x) {
in 1..10 -> print("x is in the range")
in validNumbers -> print("x is valid")
!in 10..20 -> print("x is outside the range")
else -> print("none of the above")
}
Another option is checking that a value is or !is of a particular type. Note that, due to smart casts, you can access the
methods and properties of the type without any extra checks.
when can also be used as a replacement for an if- else if chain. If no argument is supplied, the branch conditions are
simply boolean expressions, and a branch is executed when its condition is true:
when {
x.isOdd() -> print("x is odd")
y.isEven() -> print("y is even")
else -> print("x+y is odd")
}
231
fun Request.getBody() =
when (val response = executeRequest()) {
is Success -> response.body
is HttpError -> throw HttpException(response.status)
}
The scope of variable introduced in when subject is restricted to the body of this when.
For
loops
The for loop iterates through anything that provides an iterator. This is equivalent to the foreach loop in languages like C#.
The syntax of for is the following:
As mentioned before, for iterates through anything that provides an iterator. This means that it:
fun main() {
//sampleStart
for (i in 1..3) {
println(i)
}
for (i in 6 downTo 0 step 2) {
println(i)
}
//sampleEnd
}
A for loop over a range or an array is compiled to an index-based loop that does not create an iterator object.
If you want to iterate through an array or a list with an index, you can do it this way:
fun main() {
val array = arrayOf("a", "b", "c")
232
//sampleStart
for (i in array.indices) {
println(array[i])
}
//sampleEnd
}
fun main() {
val array = arrayOf("a", "b", "c")
//sampleStart
for ((index, value) in array.withIndex()) {
println("the element at $index is $value")
}
//sampleEnd
}
While
loops
while and do-while loops execute their body continuously while their condition is satisfied. The difference between them is
the condition checking time:
while checks the condition and, if it's satisfied, executes the body and then returns to the condition check.
do-while executes the body and then checks the condition. If it's satisfied, the loop repeats. So, the body of do-while
executes at least once regardless of the condition.
while (x > 0) {
x--
}
do {
val y = retrieveData()
} while (y != null) // y is visible here!
Break
and
continue
in
loops
Kotlin supports traditional break and continue operators in loops. See Returns and jumps.
Returns
and
jumps
Kotlin has three structural jump expressions:
return by default returns from the nearest enclosing function or anonymous function
233
break terminates the nearest enclosing loop
Break
and
continue
labels
Any expression in Kotlin may be marked with a label. Labels have the form of an identifier followed by the @ sign, for
example: abc@, fooBar@. To label an expression, just add a label in front of it.
A break qualified with a label jumps to the execution point right after the loop marked with that label. A continue proceeds
to the next iteration of that loop.
Return
at
labels
With function literals, local functions and object expressions, functions can be nested in Kotlin. Qualified return s allow us
to return from an outer function. The most important use case is returning from a lambda expression. Recall that when we
write this:
//sampleStart
fun foo() {
listOf(1, 2, 3, 4, 5).forEach {
if (it == 3) return // non-local return directly to the caller of foo()
print(it)
}
println("this point is unreachable")
}
//sampleEnd
fun main() {
234
foo()
}
The return -expression returns from the nearest enclosing function - foo. Note that such non-local returns are supported
only for lambda expressions passed to inline functions. To return from a lambda expression, label it and qualify the return:
//sampleStart
fun foo() {
listOf(1, 2, 3, 4, 5).forEach lit@{
if (it == 3) return@lit // local return to the caller of the lambda - the forEach loop
print(it)
}
print(" done with explicit label")
}
//sampleEnd
fun main() {
foo()
}
Now, it returns only from the lambda expression. Oftentimes it is more convenient to use implicit labels: such a label has
the same name as the function to which the lambda is passed.
//sampleStart
fun foo() {
listOf(1, 2, 3, 4, 5).forEach {
if (it == 3) return@forEach // local return to the caller of the lambda - the forEach
loop
print(it)
}
print(" done with implicit label")
}
//sampleEnd
fun main() {
foo()
}
Alternatively, you can replace the lambda expression with an anonymous function. A return statement in an anonymous
function will return from the anonymous function itself.
//sampleStart
fun foo() {
listOf(1, 2, 3, 4, 5).forEach(fun(value: Int) {
if (value == 3) return // local return to the caller of the anonymous function - the
forEach loop
print(value)
})
print(" done with anonymous function")
}
//sampleEnd
fun main() {
foo()
235
}
Note that the use of local returns in previous three examples is similar to the use of continue in regular loops. There is no
direct equivalent for break, but it can be simulated by adding another nesting lambda and non-locally returning from it:
//sampleStart
fun foo() {
run loop@{
listOf(1, 2, 3, 4, 5).forEach {
if (it == 3) return@loop // non-local return from the lambda passed to run
print(it)
}
}
print(" done with nested loop")
}
//sampleEnd
fun main() {
foo()
}
When returning a value, the parser gives preference to the qualified return:
return@a 1
This means "return 1 at label @a" and not "return a labeled expression (@a 1)".
Exceptions
Exception
classes
All exception classes in Kotlin inherit the Throwable class. Every exception has a message, a stack trace, and an optional
cause.
fun main() {
//sampleStart
throw Exception("Hi There!")
//sampleEnd
}
try {
// some code
} catch (e: SomeException) {
236
// handler
} finally {
// optional finally block
}
There may be zero or more catch blocks, and the finally block may be omitted. However, at least one catch or finally block
is required.
Try
is
an
expression
try is an expression, which means it can have a return value:
The returned value of a try expression is either the last expression in the try block or the last expression in the catch block
(or blocks). The contents of the finally block don't affect the result of the expression.
Checked
exceptions
Kotlin does not have checked exceptions. There are many reasons for this, but we will provide a simple example that
illustrates why it is the case.
The following is an example interface from the JDK implemented by the StringBuilder class:
This signature says that every time I append a string to something (a StringBuilder, some kind of a log, a console, etc.), I
have to catch the IOExceptions. Why? Because the implementation might be performing IO operations (Writer also
implements Appendable). The result is code like this all over the place.:
try {
log.append(message)
} catch (IOException e) {
// Must be safe
}
And that’s not good. Just take a look at Effective Java, 3rd Edition, Item 77: Don't ignore exceptions.
Examination of small programs leads to the conclusion that requiring exception specifications could both
enhance developer productivity and enhance code quality, but experience with large software projects
suggests a different result – decreased productivity and little or no increase in code quality.
237
And here are some additional thoughts on the matter:
If you want to alert callers about possible exceptions when calling Kotlin code from Java, Swift, or Objective-C, you can
use the @Throws annotation. Read more about using this annotation for Java and for Swift and Objective-C.
The
Nothing
type
throw is an expression in Kotlin, so you can use it, for example, as part of an Elvis expression:
The throw expression has the type Nothing. This type has no values and is used to mark code locations that can never be
reached. In your own code, you can use Nothing to mark a function that never returns:
When you call this function, the compiler will know that the execution doesn't continue beyond the call:
You may also encounter this type when dealing with type inference. The nullable variant of this type, Nothing?, has
exactly one possible value, which is null. If you use null to initialize a value of an inferred type and there's no other
information that can be used to determine a more specific type, the compiler will infer the Nothing? type:
Java
interoperability
Please see the section on exceptions in the Java interoperability page for information about Java interoperability.
Packages
and
imports
A source file may start with a package declaration:
238
package org.example
// ...
All the contents, such as classes and functions, of the source file are included in this package. So, in the example above,
the full name of printMessage() is org.example.printMessage, and the full name of Message is org.example.Message.
If the package is not specified, the contents of such a file belong to the default package with no name.
Default
imports
A number of packages are imported into every Kotlin file by default:
kotlin.*
kotlin.annotation.*
kotlin.collections.*
kotlin.comparisons.*
kotlin.io.*
kotlin.ranges.*
kotlin.sequences.*
kotlin.text.*
JVM:
java.lang.*
kotlin.jvm.*
JS:
kotlin.js.*
Imports
Apart from the default imports, each file may contain its own import directives.
239
import org.example.Message // Message is now accessible without qualification
or all the accessible contents of a scope: package, class, object, and so on:
If there is a name clash, you can disambiguate by using as keyword to locally rename the clashing entity:
The import keyword is not restricted to importing classes; you can also use it to import other declarations:
enum constants
Visibility
of
top-level
declarations
If a top-level declaration is marked private, it is private to the file it's declared in (see Visibility modifiers).
Classes
Classes in Kotlin are declared using the keyword class:
The class declaration consists of the class name, the class header (specifying its type parameters, the primary
constructor, and some other things), and the class body surrounded by curly braces. Both the header and the body are
optional; if the class has no body, the curly braces can be omitted.
class Empty
Constructors
A class in Kotlin can have a primary constructor and one or more secondary constructors. The primary constructor is a
part of the class header, and it goes after the class name and optional type parameters.
240
If the primary constructor does not have any annotations or visibility modifiers, the constructor keyword can be omitted:
The primary constructor cannot contain any code. Initialization code can be placed in initializer blocks prefixed with the
init keyword.
During the initialization of an instance, the initializer blocks are executed in the same order as they appear in the class
body, interleaved with the property initializers:
//sampleStart
class InitOrderDemo(name: String) {
val firstProperty = "First property: $name".also(::println)
init {
println("First initializer block that prints ${name}")
}
val secondProperty = "Second property: ${name.length}".also(::println)
init {
println("Second initializer block that prints ${name.length}")
}
}
//sampleEnd
fun main() {
InitOrderDemo("hello")
}
Primary constructor parameters can be used in the initializer blocks. They can also be used in property initializers
declared in the class body:
Kotlin has a concise syntax for declaring properties and initializing them from the primary constructor:
class Person(val firstName: String, val lastName: String, var age: Int)
Such declarations can also include default values of the class properties:
class Person(val firstName: String, val lastName: String, var isEmployed: Boolean = true)
You can use a trailing comma when you declare class properties:
class Person(
241
val firstName: String,
val lastName: String,
var age: Int, // trailing comma
) { /*...*/ }
Much like regular properties, properties declared in the primary constructor can be mutable (var) or read-only (val).
If the constructor has annotations or visibility modifiers, the constructor keyword is required and the modifiers go before
it:
Secondary
constructors
A class can also declare secondary constructors, which are prefixed with constructor:
class Pet {
constructor(owner: Person) {
owner.pets.add(this) // adds this pet to the list of its owner's pets
}
}
If the class has a primary constructor, each secondary constructor needs to delegate to the primary constructor, either
directly or indirectly through another secondary constructor(s). Delegation to another constructor of the same class is
done using the this keyword:
Code in initializer blocks effectively becomes part of the primary constructor. Delegation to the primary constructor
happens as the first statement of a secondary constructor, so the code in all initializer blocks and property initializers is
executed before the body of the secondary constructor.
Even if the class has no primary constructor, the delegation still happens implicitly, and the initializer blocks are still
executed:
//sampleStart
class Constructors {
init {
println("Init block")
}
242
constructor(i: Int) {
println("Constructor $i")
}
}
//sampleEnd
fun main() {
Constructors(1)
}
If a non-abstract class does not declare any constructors (primary or secondary), it will have a generated primary
constructor with no arguments. The visibility of the constructor will be public.
If you don't want your class to have a public constructor, declare an empty primary constructor with non-default visibility:
On the JVM, if all of the primary constructor parameters have default values, the compiler will generate an
additional parameterless constructor which will use the default values. This makes it easier to use Kotlin with
libraries such as Jackson or JPA that create class instances through parameterless constructors.
Creating
instances
of
classes
To create an instance of a class, call the constructor as if it were a regular function:
The process of creating instances of nested, inner, and anonymous inner classes is described in Nested classes.
Class
members
Classes can contain:
243
Functions
Properties
Object declarations
Inheritance
Classes can be derived from each other and form inheritance hierarchies. Learn more about inheritance in Kotlin.
Abstract
classes
A class may be declared abstract, along with some or all of its members. An abstract member does not have an
implementation in its class. You don't need to annotate abstract classes or functions with open.
Companion
objects
If you need to write a function that can be called without having a class instance but that needs access to the internals of
a class (such as a factory method), you can write it as a member of an object declaration inside that class.
Even more specifically, if you declare a companion object inside your class, you can access its members using only the
244
class name as a qualifier.
Inheritance
All classes in Kotlin have a common superclass, Any, which is the default superclass for a class with no supertypes
declared:
Any has three methods: equals(), hashCode(), and toString(). Thus, these methods are defined for all Kotlin classes.
By default, Kotlin classes are final – they can’t be inherited. To make a class inheritable, mark it with the open
keyword:
To declare an explicit supertype, place the type after a colon in the class header:
If the derived class has a primary constructor, the base class can (and must) be initialized in that primary constructor
according to its parameters.
If the derived class has no primary constructor, then each secondary constructor has to initialize the base type using the
super keyword or it has to delegate to another constructor which does. Note that in this case different secondary
constructors can call different constructors of the base type:
Overriding
methods
Kotlin requires explicit modifiers for overridable members and overrides:
245
class Circle() : Shape() {
override fun draw() { /*...*/ }
}
The override modifier is required for Circle.draw(). If it were missing, the compiler would complain. If there is no open
modifier on a function, like Shape.fill(), declaring a method with the same signature in a subclass is not allowed, either
with override or without it. The open modifier has no effect when added to members of a final class – a class without an
open modifier.
A member marked override is itself open, so it may be overridden in subclasses. If you want to prohibit re-overriding, use
final:
Overriding
properties
The overriding mechanism works on properties in the same way that it does on methods. Properties declared on a
superclass that are then redeclared on a derived class must be prefaced with override, and they must have a compatible
type. Each declared property can be overridden by a property with an initializer or by a property with a get method:
You can also override a val property with a var property, but not vice versa. This is allowed because a val property
essentially declares a get method, and overriding it as a var additionally declares a set method in the derived class.
Note that you can use the override keyword as part of the property declaration in a primary constructor:
interface Shape {
val vertexCount: Int
}
Derived
class
initialization
order
246
During the construction of a new instance of a derived class, the base class initialization is done as the first step
(preceded only by evaluation of the arguments for the base class constructor), which means that it happens before the
initialization logic of the derived class is run.
//sampleStart
open class Base(val name: String) {
class Derived(
name: String,
val lastName: String,
) : Base(name.replaceFirstChar { it.uppercase() }.also { println("Argument for the base class:
$it") }) {
fun main() {
println("Constructing the derived class(\"hello\", \"world\")")
Derived("hello", "world")
}
This means that when the base class constructor is executed, the properties declared or overridden in the derived class
have not yet been initialized. Using any of those properties in the base class initialization logic (either directly or indirectly
through another overridden open member implementation) may lead to incorrect behavior or a runtime failure. When
designing a base class, you should therefore avoid using open members in the constructors, property initializers, or init
blocks.
Calling
the
superclass
implementation
Code in a derived class can call its superclass functions and property accessor implementations using the super
keyword:
247
val fillColor: String get() = super.borderColor
}
Inside an inner class, accessing the superclass of the outer class is done using the super keyword qualified with the outer
class name: super@Outer:
//sampleStart
class FilledRectangle: Rectangle() {
override fun draw() {
val filler = Filler()
filler.drawAndFill()
}
inner class Filler {
fun fill() { println("Filling") }
fun drawAndFill() {
super@FilledRectangle.draw() // Calls Rectangle's implementation of draw()
fill()
println("Drawn a filled rectangle with color ${super@FilledRectangle.borderColor}")
// Uses Rectangle's implementation of borderColor's get()
}
}
}
//sampleEnd
fun main() {
val fr = FilledRectangle()
fr.draw()
}
Overriding
rules
In Kotlin, implementation inheritance is regulated by the following rule: if a class inherits multiple implementations of the
same member from its immediate superclasses, it must override this member and provide its own implementation
(perhaps, using one of the inherited ones).
To denote the supertype from which the inherited implementation is taken, use super qualified by the supertype name in
angle brackets, such as super<Base>:
interface Polygon {
fun draw() { /* ... */ } // interface members are 'open' by default
}
248
class Square() : Rectangle(), Polygon {
// The compiler requires draw() to be overridden:
override fun draw() {
super<Rectangle>.draw() // call to Rectangle.draw()
super<Polygon>.draw() // call to Polygon.draw()
}
}
It's fine to inherit from both Rectangle and Polygon, but both of them have their implementations of draw(), so you need to
override draw() in Square and provide a separate implementation for it to eliminate the ambiguity.
Properties
Declaring
properties
Properties in Kotlin classes can be declared either as mutable, using the var keyword, or as read-only, using the val
keyword.
class Address {
var name: String = "Holmes, Sherlock"
var street: String = "Baker"
var city: String = "London"
var state: String? = null
var zip: String = "123456"
}
Getters
and
setters
The full syntax for declaring a property is as follows:
The initializer, getter, and setter are optional. The property type is optional if it can be inferred from the initializer or from
249
the initializer’s or the getter’s return type, as shown below:
The full syntax of a read-only property declaration differs from a mutable one in two ways: it starts with val instead of var
and does not allow a setter:
val simple: Int? // has type Int, default getter, must be initialized in constructor
val inferredType = 1 // has type Int and a default getter
You can define custom accessors for a property. If you define a custom getter, it will be called every time you access the
property (this way you can implement a computed property). Here's an example of a custom getter:
//sampleStart
class Rectangle(val width: Int, val height: Int) {
val square: Int
get() = this.width * this.height
}
//sampleEnd
fun main() {
val rectangle = Rectangle(3, 4)
println("Width=${rectangle.width}, height=${rectangle.height}, square=${rectangle.square}")
}
You can omit the property type if it can be inferred from the getter:
If you define a custom setter, it will be called every time you assign a value to the property, except its initialization. A
custom setter looks like this:
By convention, the name of the setter parameter is value, but you can choose a different name if you prefer.
If you need to annotate an accessor or change its visibility, but you don't need to change the default implementation, you
can define the accessor without defining its body:
250
Backing
fields
In Kotlin, a field is only used as a part of a property to hold its value in memory. Fields cannot be declared directly.
However, when a property needs a backing field, Kotlin provides it automatically. This backing field can be referenced in
the accessors using the field identifier:
The field identifier can only be used in the accessors of the property.
A backing field will be generated for a property if it uses the default implementation of at least one of the accessors, or if a
custom accessor references it through the field identifier.
Backing
properties
If you want to do something that does not fit into this implicit backing field scheme, you can always fall back to having a
backing property:
On the JVM: Access to private properties with default getters and setters is optimized to avoid function call
overhead.
Compile-time
constants
If the value of a read-only property is known at compile time, mark it as a compile time constant using the const modifier.
Such a property needs to fulfil the following requirements:
251
It must be initialized with a value of type String or a primitive type
Late-initialized
properties
and
variables
Normally, properties declared as having a non-null type must be initialized in the constructor. However, it is often the case
that doing so is not convenient. For example, properties can be initialized through dependency injection, or in the setup
method of a unit test. In these cases, you cannot supply a non-null initializer in the constructor, but you still want to avoid
null checks when referencing the property inside the body of a class.
To handle such cases, you can mark the property with the lateinit modifier:
This modifier can be used on var properties declared inside the body of a class (not in the primary constructor, and only
when the property does not have a custom getter or setter), as well as for top-level properties and local variables. The
type of the property or variable must be non-null, and it must not be a primitive type.
Accessing a lateinit property before it has been initialized throws a special exception that clearly identifies the property
being accessed and the fact that it hasn't been initialized.
Checking
whether
a
lateinit
var
is
initialized
To check whether a lateinit var has already been initialized, use .isInitialized on the reference to that property:
if (foo::bar.isInitialized) {
println(foo.bar)
}
This check is only available for properties that are lexically accessible when declared in the same type, in one of the outer
types, or at top level in the same file.
252
Overriding
properties
See Overriding properties
Delegated
properties
The most common kind of property simply reads from (and maybe writes to) a backing field, but custom getters and
setters allow you to use properties so one can implement any sort of behavior of a property. Somewhere in between the
simplicity of the first kind and variety of the second, there are common patterns for what properties can do. A few
examples: lazy values, reading from a map by a given key, accessing a database, notifying a listener on access.
Interfaces
Interfaces in Kotlin can contain declarations of abstract methods, as well as method implementations. What makes them
different from abstract classes is that interfaces cannot store a state. They can have properties, but these need to be
abstract or provide accessor implementations.
interface MyInterface {
fun bar()
fun foo() {
// optional body
}
}
Implementing
interfaces
A class or object can implement one or more interfaces:
Properties
in
interfaces
You can declare properties in interfaces. A property declared in an interface can either be abstract or provide
implementations for accessors. Properties declared in interfaces can't have backing fields, and therefore accessors
253
declared in interfaces can't reference them:
interface MyInterface {
val prop: Int // abstract
fun foo() {
print(prop)
}
}
Interfaces
Inheritance
An interface can derive from other interfaces, meaning it can both provide implementations for their members and declare
new functions and properties. Quite naturally, classes implementing such an interface are only required to define the
missing implementations:
interface Named {
val name: String
}
Resolving
overriding
conflicts
When you declare many types in your supertype list, you may inherit more than one implementation of the same method:
interface A {
fun foo() { print("A") }
fun bar()
}
interface B {
254
fun foo() { print("B") }
fun bar() { print("bar") }
}
class C : A {
override fun bar() { print("bar") }
}
class D : A, B {
override fun foo() {
super<A>.foo()
super<B>.foo()
}
Interfaces A and B both declare functions foo() and bar(). Both of them implement foo(), but only B implements bar() (bar()
is not marked as abstract in A, because this is the default for interfaces if the function has no body). Now, if you derive a
concrete class C from A, you have to override bar() and provide an implementation.
However, if you derive D from A and B, you need to implement all the methods that you have inherited from multiple
interfaces, and you need to specify how exactly D should implement them. This rule applies both to methods for which
you've inherited a single implementation (bar()) and to those for which you've inherited multiple implementations (foo()).
Functional
(SAM)
interfaces
An interface with only one abstract method is called a functional interface, or a Single Abstract Method (SAM) interface.
The functional interface can have several non-abstract members but only one abstract member.
SAM
conversions
For functional interfaces, you can use SAM conversions that help make your code more concise and readable by using
lambda expressions.
Instead of creating a class that implements a functional interface manually, you can use a lambda expression. With a
SAM conversion, Kotlin can convert any lambda expression whose signature matches the signature of the interface's
single method into the code, which dynamically instantiates the interface implementation.
255
fun interface IntPredicate {
fun accept(i: Int): Boolean
}
If you don't use a SAM conversion, you will need to write code like this:
By leveraging Kotlin's SAM conversion, you can write the following equivalent code instead:
fun main() {
println("Is 7 even? - ${isEven.accept(7)}")
}
Functional
interfaces
vs.
type
aliases
Functional interfaces and type aliases serve different purposes. Type aliases are just names for existing types – they
don't create a new type, while functional interfaces do. You can provide extensions that are specific to a particular
functional interface to be inapplicable for plain functions or their type aliases.
Type aliases can have only one member, while functional interfaces can have multiple non-abstract members and one
abstract member. Functional interfaces can also implement and extend other interfaces.
Functional interfaces are more flexible and provide more capabilities than type aliases, but they can be more costly both
syntactically and at runtime because they can require conversions to a specific interface. When you choose which one to
use in your code, consider your needs:
If your API needs to accept a function (any function) with some specific parameter and return types – use a simple
functional type or define a type alias to give a shorter name to the corresponding functional type.
256
If your API accepts a more complex entity than a function – for example, it has non-trivial contracts and/or
operations on it that can't be expressed in a functional type's signature – declare a separate functional interface for
it.
Visibility
modifiers
Classes, objects, interfaces, constructors, and functions, as well as properties and their setters, can have visibility
modifiers. Getters always have the same visibility as their properties.
There are four visibility modifiers in Kotlin: private, protected, internal, and public. The default visibility is public.
On this page, you'll learn how the modifiers apply to different types of declaring scopes.
Packages
Functions, properties, classes, objects, and interfaces can be declared at the "top-level" directly inside a package:
If you don’t use a visibility modifier, public is used by default, which means that your declarations will be visible
everywhere.
If you mark a declaration as private, it will only be visible inside the file that contains the declaration.
To use a visible top-level declaration from another package, you should import it.
Examples:
257
Class
members
For members declared inside a class:
private means that the member is visible inside this class only (including all its members).
protected means that the member has the same visibility as one marked as private, but that it is also visible in
subclasses.
internal means that any client inside this module who sees the declaring class sees its internal members.
public means that any client who sees the declaring class sees its public members.
In Kotlin, an outer class does not see private members of its inner classes.
If you override a protected or an internal member and do not specify the visibility explicitly, the overriding member will
also have the same visibility as the original.
Examples:
Constructors
Use the following syntax to specify the visibility of the primary constructor of a class:
258
You need to add an explicit constructor keyword.
Here the constructor is private. By default, all constructors are public, which effectively amounts to them being visible
everywhere the class is visible (this means that a constructor of an internal class is only visible within the same module).
Local
declarations
Local variables, functions, and classes can't have visibility modifiers.
Modules
The internal visibility modifier means that the member is visible within the same module. More specifically, a module is a
set of Kotlin files compiled together, for example:
A Maven project.
A Gradle source set (with the exception that the test source set can access the internal declarations of main).
A set of files compiled with one invocation of the <kotlinc> Ant task.
Extensions
Kotlin provides the ability to extend a class with new functionality without having to inherit from the class or use design
patterns such as Decorator. This is done via special declarations called extensions.
For example, you can write new functions for a class from a third-party library that you can't modify. Such functions can
be called in the usual way, as if they were methods of the original class. This mechanism is called an extension function.
There are also extension properties that let you define new properties for existing classes.
Extension
functions
To declare an extension function, prefix its name with a receiver type, which refers to the type being extended. The
following adds a swap function to MutableList<Int>:
259
}
The this keyword inside an extension function corresponds to the receiver object (the one that is passed before the dot).
Now, you can call such a function on any MutableList<Int>:
This function makes sense for any MutableList<T>, and you can make it generic:
You need to declare the generic type parameter before the function name to make it available in the receiver type
expression. For more information about generics, see generic functions.
Extensions
are
resolved
statically
Extensions do not actually modify the classes they extend. By defining an extension, you are not inserting new members
into a class, only making new functions callable with the dot-notation on variables of this type.
Extension functions are dispatched statically, which means they are not virtual by receiver type. An extension function
being called is determined by the type of the expression on which the function is invoked, not by the type of the result
from evaluating that expression at runtime. For example:
fun main() {
//sampleStart
open class Shape
class Rectangle: Shape()
fun Shape.getName() = "Shape"
fun Rectangle.getName() = "Rectangle"
fun printClassName(s: Shape) {
println(s.getName())
}
printClassName(Rectangle())
//sampleEnd
}
This example prints Shape, because the extension function called depends only on the declared type of the parameter s,
which is the Shape class.
If a class has a member function, and an extension function is defined which has the same receiver type, the same name,
and is applicable to given arguments, the member always wins. For example:
260
fun main() {
//sampleStart
class Example {
fun printFunctionType() { println("Class method") }
}
fun Example.printFunctionType() { println("Extension function") }
Example().printFunctionType()
//sampleEnd
}
However, it's perfectly OK for extension functions to overload member functions that have the same name but a different
signature:
fun main() {
//sampleStart
class Example {
fun printFunctionType() { println("Class method") }
}
fun Example.printFunctionType(i: Int) { println("Extension function #$i") }
Example().printFunctionType(1)
//sampleEnd
}
Nullable
receiver
Note that extensions can be defined with a nullable receiver type. These extensions can be called on an object variable
even if its value is null, and they can check for this == null inside the body.
This way, you can call toString() in Kotlin without checking for null, as the check happens inside the extension function:
Extension
properties
Kotlin supports extension properties much like it supports functions:
261
Since extensions do not actually insert members into classes, there's no efficient way for an extension property
to have a backing field. This is why initializers are not allowed for extension properties. Their behavior can only
be defined by explicitly providing getters/setters.
Example:
val House.number = 1 // error: initializers are not allowed for extension properties
Companion
object
extensions
If a class has a companion object defined, you can also define extension functions and properties for the companion
object. Just like regular members of the companion object, they can be called using only the class name as the qualifier:
class MyClass {
companion object { } // will be called "Companion"
}
fun main() {
MyClass.printCompanion()
}
Scope
of
extensions
In most cases, you define extensions on the top level, directly under packages:
package org.example.declarations
To use an extension outside its declaring package, import it at the call site:
package org.example.usage
import org.example.declarations.getLongestString
fun main() {
val list = listOf("red", "green", "blue")
list.getLongestString()
}
262
See Imports for more information.
Declaring
extensions
as
members
You can declare extensions for one class inside another class. Inside such an extension, there are multiple implicit
receivers- objects whose members can be accessed without a qualifier. An instance of a class in which the extension is
declared is called a dispatch receiver, and an instance of the receiver type of the extension method is called an extension
receiver.
fun Host.printConnectionString() {
printHostname() // calls Host.printHostname()
print(":")
printPort() // calls Connection.printPort()
}
fun connect() {
/*...*/
host.printConnectionString() // calls the extension function
}
}
fun main() {
Connection(Host("kotl.in"), 443).connect()
//Host("kotl.in").printConnectionString() // error, the extension function is unavailable
outside Connection
}
In the event of a name conflict between the members of a dispatch receiver and an extension receiver, the extension
receiver takes precedence. To refer to the member of the dispatch receiver, you can use the qualified this syntax.
class Connection {
fun Host.getConnectionString() {
toString() // calls Host.toString()
this@Connection.toString() // calls Connection.toString()
}
}
Extensions declared as members can be declared as open and overridden in subclasses. This means that the dispatch of
such functions is virtual with regard to the dispatch receiver type, but static with regard to the extension receiver type.
263
open fun Base.printFunctionInfo() {
println("Base extension function in BaseCaller")
}
fun main() {
BaseCaller().call(Base()) // "Base extension function in BaseCaller"
DerivedCaller().call(Base()) // "Base extension function in DerivedCaller" - dispatch
receiver is resolved virtually
DerivedCaller().call(Derived()) // "Base extension function in DerivedCaller" - extension
receiver is resolved statically
}
Note
on
visibility
Extensions utilize the same visibility modifiers as regular functions declared in the same scope would. For example:
An extension declared at the top level of a file has access to the other private top-level declarations in the same file.
If an extension is declared outside its receiver type, it cannot access the receiver's private or protected members.
Data
classes
It is not unusual to create classes whose main purpose is to hold data. In such classes, some standard functionality and
some utility functions are often mechanically derivable from the data. In Kotlin, these are called data classes and are
marked with data:
The compiler automatically derives the following members from all properties declared in the primary constructor:
264
toString() of the form "User(name=John, age=42)"
To ensure consistency and meaningful behavior of the generated code, data classes have to fulfill the following
requirements:
Additionally, the generation of data class members follows these rules with regard to the members’ inheritance:
If there are explicit implementations of equals(), hashCode(), or toString() in the data class body or final
implementations in a superclass, then these functions are not generated, and the existing implementations are used.
If a supertype has componentN() functions that are open and return compatible types, the corresponding functions are
generated for the data class and override those of the supertype. If the functions of the supertype cannot be
overridden due to incompatible signatures or due to their being final, an error is reported.
Providing explicit implementations for the componentN() and copy() functions is not allowed.
Data classes may extend other classes (see Sealed classes for examples).
On the JVM, if the generated class needs to have a parameterless constructor, default values for the properties
have to be specified (see Constructors).
Properties
declared
in
the
class
body
The compiler only uses the properties defined inside the primary constructor for the automatically generated functions. To
exclude a property from the generated implementations, declare it inside the class body:
Only the property name will be used inside the toString(), equals(), hashCode(), and copy() implementations, and there will
only be one component function component1(). While two Person objects can have different ages, they will be treated as
equal.
265
data class Person(val name: String) {
var age: Int = 0
}
fun main() {
//sampleStart
val person1 = Person("John")
val person2 = Person("John")
person1.age = 10
person2.age = 20
//sampleEnd
println("person1 == person2: ${person1 == person2}")
println("person1 with age ${person1.age}: ${person1}")
println("person2 with age ${person2.age}: ${person2}")
}
Copying
Use the copy() function to copy an object, allowing you to alter some of its properties while keeping the rest unchanged.
The implementation of this function for the User class above would be as follows:
Data
classes
and
destructuring
declarations
Component functions generated for data classes make it possible to use them in destructuring declarations:
Standard
data
classes
The standard library provides the Pair and Triple classes. In most cases, though, named data classes are a better design
choice because they make the code more readable by providing meaningful names for the properties.
Sealed
classes
Sealed classes and interfaces represent restricted class hierarchies that provide more control over inheritance. All direct
266
subclasses of a sealed class are known at compile time. No other subclasses may appear after a module with the sealed
class is compiled. For example, third-party clients can't extend your sealed class in their code. Thus, each instance of a
sealed class has a type from a limited set that is known when this class is compiled.
The same works for sealed interfaces and their implementations: once a module with a sealed interface is compiled, no
new implementations can appear.
In some sense, sealed classes are similar to enum classes: the set of values for an enum type is also restricted, but each
enum constant exists only as a single instance, whereas a subclass of a sealed class can have multiple instances, each
with its own state.
As an example, consider a library's API. It's likely to contain error classes to let the library users handle errors that it can
throw. If the hierarchy of such error classes includes interfaces or abstract classes visible in the public API, then nothing
prevents implementing or extending them in the client code. However, the library doesn't know about errors declared
outside it, so it can't treat them consistently with its own classes. With a sealed hierarchy of error classes, library authors
can be sure that they know all possible error types and no other ones can appear later.
To declare a sealed class or interface, put the sealed modifier before its name:
A sealed class is abstract by itself, it cannot be instantiated directly and can have abstract members.
Constructors of sealed classes can have one of two visibilities: protected (by default) or private:
Location
of
direct
subclasses
Direct subclasses of sealed classes and interfaces must be declared in the same package. They may be top-level or
nested inside any number of other named classes, named interfaces, or named objects. Subclasses can have any
visibility as long as they are compatible with normal inheritance rules in Kotlin.
Subclasses of sealed classes must have a proper qualified name. They can't be local nor anonymous objects.
267
enum classes can't extend a sealed class (as well as any other class), but they can implement sealed
interfaces.
These restrictions don't apply to indirect subclasses. If a direct subclass of a sealed class is not marked as sealed, it can
be extended in any ways that its modifiers allow:
sealed interface Error // has implementations only in same package and module
sealed class IOError(): Error // extended only in same package and module
open class CustomError(): Error // can be extended wherever it's visible
Inheritance
in
multiplatform
projects
There is one more inheritance restriction in multiplatform projects: direct subclasses of sealed classes must reside in the
same source set. It applies to sealed classes without the expect and actual modifiers.
If a sealed class is declared as expect in a common source set and have actual implementations in platform source sets,
both expect and actual versions can have subclasses in their source sets. Moreover, if you use a hierarchical structure,
you can create subclasses in any source set between the expect and actual declarations.
Sealed
classes
and
when
expression
The key benefit of using sealed classes comes into play when you use them in a when expression. If it's possible to verify
that the statement covers all cases, you don't need to add an else clause to the statement. However, this works only if
you use when as an expression (using the result) and not as a statement:
when expressions on expect sealed classes in the common code of multiplatform projects still require an else
branch. This happens because subclasses of actual platform implementations aren't known in the common
code.
Generics:
in,
out,
where
268
Classes in Kotlin can have type parameters, just like in Java:
class Box<T>(t: T) {
var value = t
}
But if the parameters can be inferred, for example, from the constructor arguments, you can omit the type arguments:
val box = Box(1) // 1 has type Int, so the compiler figures out that it is Box<Int>
Variance
One of the trickiest aspects of Java's type system is the wildcard types (see Java Generics FAQ). Kotlin doesn't have
these. Instead, Kotlin has declaration-site variance and type projections.
Let's think about why Java needs these mysterious wildcards. The problem is explained well in Effective Java, 3rd
Edition, Item 31: Use bounded wildcards to increase API flexibility. First, generic types in Java are invariant, meaning that
List<String> is not a subtype of List<Object>. If List were not invariant, it would have been no better than Java's arrays,
as the following code would have compiled but caused an exception at runtime:
// Java
List<String> strs = new ArrayList<String>();
List<Object> objs = strs; // !!! A compile-time error here saves us from a runtime exception
later.
objs.add(1); // Put an Integer into a list of Strings
String s = strs.get(0); // !!! ClassCastException: Cannot cast Integer to String
Java prohibits such things in order to guarantee run-time safety. But this has implications. For example, consider the
addAll() method from the Collection interface. What's the signature of this method? Intuitively, you'd write it this way:
// Java
interface Collection<E> ... {
void addAll(Collection<E> items);
}
But then, you would not be able to do the following (which is perfectly safe):
// Java
void copyAll(Collection<Object> to, Collection<String> from) {
to.addAll(from);
// !!! Would not compile with the naive declaration of addAll:
// Collection<String> is not a subtype of Collection<Object>
269
}
(In Java, you probably learned this the hard way, see Effective Java, 3rd Edition, Item 28: Prefer lists to arrays)
// Java
interface Collection<E> ... {
void addAll(Collection<? extends E> items);
}
The wildcard type argument ? extends E indicates that this method accepts a collection of objects of E or a subtype of E,
not just E itself. This means that you can safely read E 's from items (elements of this collection are instances of a
subclass of E), but cannot write to it as you don't know what objects comply with that unknown subtype of E. In return for
this limitation, you get the desired behavior: Collection<String> is a subtype of Collection<? extends Object>. In other
words, the wildcard with an extends -bound (upper bound) makes the type covariant.
The key to understanding why this works is rather simple: if you can only take items from a collection, then using a
collection of String s and reading Object s from it is fine. Conversely, if you can only put items into the collection, it's okay
to take a collection of Object s and put String s into it: in Java there is List<? super String>, a supertype of List<Object>.
The latter is called contravariance, and you can only call methods that take String as an argument on List<? super String>
(for example, you can call add(String) or set(int, String)). If you call something that returns T in List<T>, you don't get a
String, but rather an Object.
Joshua Bloch gives the name Producers to objects you only read from and Consumers to those you only write to. He
recommends:
"For maximum flexibility, use wildcard types on input parameters that represent producers or consumers", and
proposes the following mnemonic:
If you use a producer-object, say, List<? extends Foo>, you are not allowed to call add() or set() on this object,
but this does not mean that it is immutable: for example, nothing prevents you from calling clear() to remove all
the items from the list, since clear() does not take any parameters at all.
The only thing guaranteed by wildcards (or other types of variance) is type safety. Immutability is a completely
different story.
Declaration-site
variance
Let's suppose that there is a generic interface Source<T> that does not have any methods that take T as a parameter,
only methods that return T:
270
// Java
interface Source<T> {
T nextT();
}
Then, it would be perfectly safe to store a reference to an instance of Source<String> in a variable of type
Source<Object>- there are no consumer-methods to call. But Java does not know this, and still prohibits it:
// Java
void demo(Source<String> strs) {
Source<Object> objects = strs; // !!! Not allowed in Java
// ...
}
To fix this, you should declare objects of type Source<? extends Object>. Doing so is meaningless, because you can call
all the same methods on such a variable as before, so there's no value added by the more complex type. But the
compiler does not know that.
In Kotlin, there is a way to explain this sort of thing to the compiler. This is called declaration-site variance: you can
annotate the type parameter T of Source to make sure that it is only returned (produced) from members of Source<T>,
and never consumed. To do this, use the out modifier:
The general rule is this: when a type parameter T of a class C is declared out, it may occur only in the out -position in the
members of C, but in return C<Base> can safely be a supertype of C<Derived>.
In other words, you can say that the class C is covariant in the parameter T, or that T is a covariant type parameter. You
can think of C as being a producer of T 's, and NOT a consumer of T 's.
The out modifier is called a variance annotation, and since it is provided at the type parameter declaration site, it provides
declaration-site variance. This is in contrast with Java's use-site variance where wildcards in the type usages make the
types covariant.
In addition to out, Kotlin provides a complementary variance annotation: in. It makes a type parameter contravariant,
meaning it can only be consumed and never produced. A good example of a contravariant type is Comparable:
271
// Thus, you can assign x to a variable of type Comparable<Double>
val y: Comparable<Double> = x // OK!
}
The words in and out seem to be self-explanatory (as they’ve already been used successfully in C# for quite some
time), and so the mnemonic mentioned above is not really needed. It can in fact be rephrased at a higher level of
abstraction:
Type
projections
Use-site
variance:
type
projections
It is very easy to declare a type parameter T as out and avoid trouble with subtyping on the use site, but some classes
can't actually be restricted to only return T 's! A good example of this is Array:
This class can be neither co- nor contravariant in T. And this imposes certain inflexibilities. Consider the following
function:
This function is supposed to copy items from one array to another. Let's try to apply it in practice:
Here you run into the same familiar problem: Array<T> is invariant in T, and so neither Array<Int> nor Array<Any> is a
subtype of the other. Why not? Again, this is because copy could have an unexpected behavior, for example, it may
attempt to write a String to from, and if you actually pass an array of Int there, a ClassCastException will be thrown later.
To prohibit the copy function from writing to from, you can do the following:
272
This is type projection, which means that from is not a simple array, but is rather a restricted (projected) one. You can only
call methods that return the type parameter T, which in this case means that you can only call get(). This is our approach
to use-site variance, and it corresponds to Java's Array<? extends Object> while being slightly simpler.
Array<in String> corresponds to Java's Array<? super String>. This means that you can pass an array of CharSequence
or an array of Object to the fill() function.
Star-projections
Sometimes you want to say that you know nothing about the type argument, but you still want to use it in a safe way. The
safe way here is to define such a projection of the generic type, that every concrete instantiation of that generic type will
be a subtype of that projection.
For Foo<out T : TUpper>, where T is a covariant type parameter with the upper bound TUpper, Foo<*> is equivalent to
Foo<out TUpper>. This means that when the T is unknown you can safely read values of TUpper from Foo<*>.
For Foo<in T>, where T is a contravariant type parameter, Foo<*> is equivalent to Foo<in Nothing>. This means there
is nothing you can write to Foo<*> in a safe way when T is unknown.
For Foo<T : TUpper>, where T is an invariant type parameter with the upper bound TUpper, Foo<*> is equivalent to
Foo<out TUpper> for reading values and to Foo<in Nothing> for writing values.
If a generic type has several type parameters, each of them can be projected independently. For example, if the type is
declared as interface Function<in T, out U> you could use the following star-projections:
Star-projections are very much like Java's raw types, but safe.
Generic
functions
Classes aren’t the only declarations that can have type parameters. Functions can, too. Type parameters are placed
before the name of the function:
273
}
To call a generic function, specify the type arguments at the call site after the name of the function:
val l = singletonList<Int>(1)
Type arguments can be omitted if they can be inferred from the context, so the following example works as well:
val l = singletonList(1)
Generic
constraints
The set of all possible types that can be substituted for a given type parameter may be restricted by generic constraints.
Upper
bounds
The most common type of constraint is an upper bound, which corresponds to Java's extends keyword:
The type specified after a colon is the upper bound, indicating that only a subtype of Comparable<T> can be substituted
for T. For example:
The default upper bound (if there was none specified) is Any?. Only one upper bound can be specified inside the angle
brackets. If the same type parameter needs more than one upper bound, you need a separate where -clause:
The passed type must satisfy all conditions of the where clause simultaneously. In the above example, the T type must
implement both CharSequence and Comparable.
274
Type
erasure
The type safety checks that Kotlin performs for generic declaration usages are done at compile time. At runtime, the
instances of generic types do not hold any information about their actual type arguments. The type information is said to
be erased. For example, the instances of Foo<Bar> and Foo<Baz?> are erased to just Foo<*>.
Therefore, there is no general way to check whether an instance of a generic type was created with certain type
arguments at runtime, and the compiler prohibits such is -checks.
Type casts to generic types with concrete type arguments, for example, foo as List<String>, cannot be checked at
runtime. These unchecked casts can be used when type safety is implied by high-level program logic but cannot be
inferred directly by the compiler. The compiler issues a warning on unchecked casts, and at runtime, only the non-generic
part is checked (equivalent to foo as List<*>).
The type arguments of generic function calls are also only checked at compile time. Inside the function bodies, the type
parameters cannot be used for type checks, and type casts to type parameters (foo as T) are unchecked. However, reified
type parameters of inline functions are substituted by the actual type arguments in the inlined function body at the call
sites and so can be used for type checks and casts, with the same restrictions for instances of generic types as described
above.
Nested
and
inner
classes
Classes can be nested in other classes:
class Outer {
private val bar: Int = 1
class Nested {
fun foo() = 2
}
}
You can also use interfaces with nesting. All combinations of classes and interfaces are possible: You can nest interfaces
in classes, classes in interfaces, and interfaces in interfaces.
interface OuterInterface {
class InnerClass
interface InnerInterface
}
class OuterClass {
class InnerClass
interface InnerInterface
}
275
Inner
classes
A nested class marked as inner can access the members of its outer class. Inner classes carry a reference to an object of
an outer class:
class Outer {
private val bar: Int = 1
inner class Inner {
fun foo() = bar
}
}
See Qualified this expressions to learn about disambiguation of this in inner classes.
Anonymous
inner
classes
Anonymous inner class instances are created using an object expression:
window.addMouseListener(object : MouseAdapter() {
On the JVM, if the object is an instance of a functional Java interface (that means a Java interface with a single
abstract method), you can create it using a lambda expression prefixed with the type of the interface:
Enum
classes
The most basic use case for enum classes is the implementation of type-safe enums:
Since each enum is an instance of the enum class, it can be initialized as:
276
enum class Color(val rgb: Int) {
RED(0xFF0000),
GREEN(0x00FF00),
BLUE(0x0000FF)
}
Anonymous
classes
Enum constants can declare their own anonymous classes with their corresponding methods, as well as with overriding
base methods.
TALKING {
override fun signal() = WAITING
};
If the enum class defines any members, separate the constant definitions from the member definitions with a semicolon.
Implementing
interfaces
in
enum
classes
An enum class can implement an interface (but it cannot derive from a class), providing either a common implementation
of interface members for all of the entries, or separate implementations for each entry within its anonymous class. This is
done by adding the interfaces you want to implement to the enum class declaration as follows:
import java.util.function.BinaryOperator
import java.util.function.IntBinaryOperator
//sampleStart
enum class IntArithmetics : BinaryOperator<Int>, IntBinaryOperator {
PLUS {
override fun apply(t: Int, u: Int): Int = t + u
},
TIMES {
override fun apply(t: Int, u: Int): Int = t * u
};
override fun applyAsInt(t: Int, u: Int) = apply(t, u)
}
//sampleEnd
fun main() {
val a = 13
277
val b = 31
for (f in IntArithmetics.values()) {
println("$f($a, $b) = ${f.apply(a, b)}")
}
}
Working
with
enum
constants
Enum classes in Kotlin have synthetic methods for listing the defined enum constants and getting an enum constant by
its name. The signatures of these methods are as follows (assuming the name of the enum class is EnumClass):
The valueOf() method throws an IllegalArgumentException if the specified name does not match any of the enum
constants defined in the class.
You can access the constants in an enum class in a generic way using the enumValues<T>() and enumValueOf<T>()
functions:
Every enum constant has properties for obtaining its name and position in the enum class declaration:
The enum constants also implement the Comparable interface, with the natural order being the order in which they are
defined in the enum class.
Inline
classes
Sometimes it is necessary for business logic to create a wrapper around some type. However, it introduces runtime
overhead due to additional heap allocations. Moreover, if the wrapped type is primitive, the performance hit is terrible,
because primitive types are usually heavily optimized by the runtime, while their wrappers don't get any special treatment.
To solve such issues, Kotlin introduces a special kind of class called an inline class. Inline classes are a subset of value-
based classes. They don't have an identity and can only hold values.
278
To declare an inline class, use the value modifier before the name of the class:
To declare an inline class for the JVM backend, use the value modifier along with the @JvmInline annotation before the
class declaration:
An inline class must have a single property initialized in the primary constructor. At runtime, instances of the inline class
will be represented using this single property (see details about runtime representation below):
This is the main feature of inline classes, which inspired the name inline: data of the class is inlined into its usages (similar
to how content of inline functions is inlined to call sites).
Members
Inline classes support some functionality of regular classes. In particular, they are allowed to declare properties and
functions, and have the init block:
@JvmInline
value class Name(val s: String) {
init {
require(s.length > 0) { }
}
fun greet() {
println("Hello, $s")
}
}
fun main() {
val name = Name("Kotlin")
name.greet() // method `greet` is called as a static method
println(name.length) // property getter is called as a static method
}
279
Inline class properties cannot have backing fields. They can only have simple computable properties (no lateinit
/delegated properties).
Inheritance
Inline classes are allowed to inherit from interfaces:
interface Printable {
fun prettyPrint(): String
}
@JvmInline
value class Name(val s: String) : Printable {
override fun prettyPrint(): String = "Let's $s!"
}
fun main() {
val name = Name("Kotlin")
println(name.prettyPrint()) // Still called as a static method
}
It is forbidden for inline classes to participate in a class hierarchy. This means that inline classes cannot extend other
classes and must be final.
Representation
In generated code, the Kotlin compiler keeps a wrapper for each inline class. Inline class instances can be represented at
runtime either as wrappers or as the underlying type. This is similar to how Int can be represented either as a primitive int
or as the wrapper Integer.
The Kotlin compiler will prefer using underlying types instead of wrappers to produce the most performant and optimized
code. However, sometimes it is necessary to keep wrappers around. As a rule of thumb, inline classes are boxed
whenever they are used as another type.
interface I
@JvmInline
value class Foo(val i: Int) : I
fun main() {
val f = Foo(42)
280
asInline(f) // unboxed: used as Foo itself
asGeneric(f) // boxed: used as generic type T
asInterface(f) // boxed: used as type I
asNullable(f) // boxed: used as Foo?, which is different from Foo
// below, 'f' first is boxed (while being passed to 'id') and then unboxed (when returned
from 'id')
// In the end, 'c' contains unboxed representation (just '42'), as 'f'
val c = id(f)
}
Because inline classes may be represented both as the underlying value and as a wrapper, referential equality is pointless
for them and is therefore prohibited.
Mangling
Since inline classes are compiled to their underlying type, it may lead to various obscure errors, for example unexpected
platform signature clashes:
@JvmInline
value class UInt(val x: Int)
To mitigate such issues, functions using inline classes are mangled by adding some stable hashcode to the function
name. Therefore, fun compute(x: UInt) will be represented as public final void compute-<hashcode>(int x), which solves
the clash problem.
The mangling scheme has been changed in Kotlin 1.4.30. Use the -Xuse-14-inline-classes-mangling-scheme
compiler flag to force the compiler to use the old 1.4.0 mangling scheme and preserve binary compatibility.
Calling
from
Java
code
You can call functions that accept inline classes from Java code. To do so, you should manually disable mangling: add
the @JvmName annotation before the function declaration:
@JvmInline
value class UInt(val x: Int)
@JvmName("computeUInt")
fun compute(x: UInt) { }
281
Inline
classes
vs
type
aliases
At first sight, inline classes seem very similar to type aliases. Indeed, both seem to introduce a new type and both will be
represented as the underlying type at runtime.
However, the crucial difference is that type aliases are assignment-compatible with their underlying type (and with other
type aliases with the same underlying type), while inline classes are not.
In other words, inline classes introduce a truly new type, contrary to type aliases which only introduce an alternative name
(alias) for an existing type:
@JvmInline
value class NameInlineClass(val s: String)
fun main() {
val nameAlias: NameTypeAlias = ""
val nameInlineClass: NameInlineClass = NameInlineClass("")
val string: String = ""
Object
expressions
and
declarations
Sometimes you need to create an object that is a slight modification of some class, without explicitly declaring a new
subclass for it. Kotlin can handle this with object expressions and object declarations.
Object
expressions
Object expressions create objects of anonymous classes, that is, classes that aren't explicitly declared with the class
declaration. Such classes are useful for one-time use. You can define them from scratch, inherit from existing classes, or
implement interfaces. Instances of anonymous classes are also called anonymous objects because they are defined by
an expression, not a name.
Creating
anonymous
objects
from
scratch
Object expressions start with the object keyword.
282
If you just need an object that doesn’t have any nontrivial supertypes, write its members in curly braces after object:
fun main() {
//sampleStart
val helloWorld = object {
val hello = "Hello"
val world = "World"
// object expressions extend Any, so `override` is required on `toString()`
override fun toString() = "$hello $world"
}
//sampleEnd
print(helloWorld)
}
Inheriting
anonymous
objects
from
supertypes
To create an object of an anonymous class that inherits from some type (or types), specify this type after object and a
colon (:). Then implement or override the members of this class as if you were inheriting from it:
window.addMouseListener(object : MouseAdapter() {
override fun mouseClicked(e: MouseEvent) { /*...*/ }
If a supertype has a constructor, pass appropriate constructor parameters to it. Multiple supertypes can be specified as a
comma-delimited list after the colon:
interface B { /*...*/ }
Using
anonymous
objects
as
return
and
value
types
When an anonymous object is used as a type of a local or private but not inline declaration (function or property), all its
members are accessible via this function or property:
class C {
private fun getObject() = object {
val x: String = "x"
}
fun printX() {
println(getObject().x)
283
}
}
If this function or property is public or private inline, its actual type is:
The declared supertype of the anonymous object, if there is exactly one such type
The explicitly declared type if there is more than one declared supertype
In all these cases, members added in the anonymous object are not accessible. Overridden members are accessible if
they are declared in the actual type of the function or property:
interface A {
fun funFromA() {}
}
interface B
class C {
// The return type is Any. x is not accessible
fun getObject() = object {
val x: String = "x"
}
Accessing
variables
from
anonymous
objects
The code in object expressions can access variables from the enclosing scope:
window.addMouseListener(object : MouseAdapter() {
override fun mouseClicked(e: MouseEvent) {
clickCount++
}
284
// ...
}
Object
declarations
The Singleton pattern can be useful in several cases, and Kotlin makes it easy to declare singletons:
object DataProviderManager {
fun registerDataProvider(provider: DataProvider) {
// ...
}
This is called an object declaration, and it always has a name following the object keyword. Just like a variable
declaration, an object declaration is not an expression, and it cannot be used on the right-hand side of an assignment
statement.
DataProviderManager.registerDataProvider(...)
Object declarations can't be local (that is, they can't be nested directly inside a function), but they can be
nested into other object declarations or non-inner classes.
Companion
objects
An object declaration inside a class can be marked with the companion keyword:
class MyClass {
companion object Factory {
fun create(): MyClass = MyClass()
}
}
285
Members of the companion object can be called simply by using the class name as the qualifier:
The name of the companion object can be omitted, in which case the name Companion will be used:
class MyClass {
companion object { }
}
val x = MyClass.Companion
Class members can access the private members of the corresponding companion object.
The name of a class used by itself (not as a qualifier to another name) acts as a reference to the companion object of the
class (whether named or not):
class MyClass1 {
companion object Named { }
}
val x = MyClass1
class MyClass2 {
companion object { }
}
val y = MyClass2
Note that even though the members of companion objects look like static members in other languages, at runtime those
are still instance members of real objects, and can, for example, implement interfaces:
interface Factory<T> {
fun create(): T
}
class MyClass {
companion object : Factory<MyClass> {
override fun create(): MyClass = MyClass()
}
}
However, on the JVM you can have members of companion objects generated as real static methods and fields if you use
the @JvmStatic annotation. See the Java interoperability section for more detail.
Semantic
difference
between
object
expressions
and
declarations
There is one important semantic difference between object expressions and object declarations:
286
Object expressions are executed (and initialized) immediately, where they are used.
Object declarations are initialized lazily, when accessed for the first time.
A companion object is initialized when the corresponding class is loaded (resolved) that matches the semantics of a
Java static initializer.
Delegation
The Delegation pattern has proven to be a good alternative to implementation inheritance, and Kotlin supports it natively
requiring zero boilerplate code.
A class Derived can implement an interface Base by delegating all of its public members to a specified object:
interface Base {
fun print()
}
fun main() {
val b = BaseImpl(10)
Derived(b).print()
}
The by -clause in the supertype list for Derived indicates that b will be stored internally in objects of Derived and the
compiler will generate all the methods of Base that forward to b.
Overriding
a
member
of
an
interface
implemented
by
delegation
Overrides work as you expect: the compiler will use your override implementations instead of those in the delegate
object. If you want to add override fun printMessage() { print("abc") } to Derived, the program would print abc instead of
10 when printMessage is called:
interface Base {
fun printMessage()
fun printMessageLine()
}
287
class Derived(b: Base) : Base by b {
override fun printMessage() { print("abc") }
}
fun main() {
val b = BaseImpl(10)
Derived(b).printMessage()
Derived(b).printMessageLine()
}
Note, however, that members overridden in this way do not get called from the members of the delegate object, which
can only access its own implementations of the interface members:
interface Base {
val message: String
fun print()
}
fun main() {
val b = BaseImpl(10)
val derived = Derived(b)
derived.print()
println(derived.message)
}
Delegated
properties
There are certain common kinds of properties, that, though you can implement them manually every time you need them,
it would be helpful to implement them once and add to a library. Examples include:
Lazy properties: the value gets computed only upon first access.
class Example {
var p: String by Delegate()
288
}
The syntax is: val/var <property name>: <Type> by <expression>. The expression after by is a delegate, because get()
(and set()) corresponding to the property will be delegated to its getValue() and setValue() methods. Property delegates
don’t have to implement any interface, but they have to provide a getValue() function (and setValue()--- for var s).
For example:
import kotlin.reflect.KProperty
class Delegate {
operator fun getValue(thisRef: Any?, property: KProperty<*>): String {
return "$thisRef, thank you for delegating '${property.name}' to me!"
}
operator fun setValue(thisRef: Any?, property: KProperty<*>, value: String) {
println("$value has been assigned to '${property.name}' in $thisRef.")
}
}
When you read from p that delegates to an instance of Delegate, the getValue() function from Delegate is called, so that
its first parameter is the object you read p from and the second parameter holds a description of p itself (for example, you
can take its name).
val e = Example()
println(e.p)
This prints:
e.p = "NEW"
This prints
Note that you can declare a delegated property inside a function or code block, it shouldn't necessarily be a member of a
class. Below you can find an example.
Standard
delegates
The Kotlin standard library provides factory methods for several useful kinds of delegates.
289
Lazy
properties
lazy() is a function that takes a lambda and returns an instance of Lazy<T> which can serve as a delegate for
implementing a lazy property: the first call to get() executes the lambda passed to lazy() and remembers the result,
subsequent calls to get() simply return the remembered result.
fun main() {
println(lazyValue)
println(lazyValue)
}
By default, the evaluation of lazy properties is synchronized: the value is computed only in one thread, and all threads will
see the same value. If the synchronization of initialization delegate is not required, so that multiple threads can execute it
simultaneously, pass LazyThreadSafetyMode.PUBLICATION as a parameter to the lazy() function.
And if you're sure that the initialization will always happen on the same thread as the one where you use the property, you
can use LazyThreadSafetyMode.NONE: it doesn't incur any thread-safety guarantees and the related overhead.
Observable
properties
Delegates.observable() takes two arguments: the initial value and a handler for modifications.
The handler is called every time you assign to the property (after the assignment has been performed). It has three
parameters: a property being assigned to, the old value and the new one:
import kotlin.properties.Delegates
class User {
var name: String by Delegates.observable("<no name>") {
prop, old, new ->
println("$old -> $new")
}
}
fun main() {
val user = User()
user.name = "first"
user.name = "second"
}
If you want to intercept assignments and veto them, use vetoable() instead of observable(). The handler passed to the
vetoable is called before the assignment of a new property value.
Delegating
to
another
property
A property can delegate its getter and setter to another property. Such delegation is available for both top-level and class
290
properties (member and extension). The delegate property can be:
a top-level property
To delegate a property to another property, use the proper :: qualifier in the delegate name, for example, this::delegate or
MyClass::delegate.
This may be useful, for example, when you want to rename a property in a backward-compatible way: you introduce a
new property, annotate the old one with the @Deprecated annotation, and delegate its implementation.
class MyClass {
var newName: Int = 0
@Deprecated("Use 'newName' instead", ReplaceWith("newName"))
var oldName: Int by this::newName
}
fun main() {
val myClass = MyClass()
// Notification: 'oldName: Int' is deprecated.
// Use 'newName' instead
myClass.oldName = 42
println(myClass.newName) // 42
}
Storing
properties
in
a
map
One common use case is storing the values of properties in a map. This comes up often in applications like parsing JSON
or doing other “dynamic†things. In this case, you can use the map instance itself as the delegate for a delegated
property.
291
val user = User(mapOf(
"name" to "John Doe",
"age" to 25
))
Delegated properties take values from this map (by the string keys – names of properties):
fun main() {
val user = User(mapOf(
"name" to "John Doe",
"age" to 25
))
//sampleStart
println(user.name) // Prints "John Doe"
println(user.age) // Prints 25
//sampleEnd
}
This works also for var ’s properties if you use a MutableMap instead of read-only Map:
Local
delegated
properties
You can declare local variables as delegated properties. For example, you can make a local variable lazy:
The memoizedFoo variable will be computed on the first access only. If someCondition fails, the variable won't be
computed at all.
Property
delegate
requirements
Here are requirements for delegating properties.
292
For a read-only property (val), a delegate should provide an operator function getValue() with the following parameters:
thisRef must be the same or a supertype of the property owner (for extension properties, it should be the type being
extended).
getValue() must return the same type as the property (or its subtype).
class Resource
class Owner {
val valResource: Resource by ResourceDelegate()
}
class ResourceDelegate {
operator fun getValue(thisRef: Owner, property: KProperty<*>): Resource {
return Resource()
}
}
For a mutable property (var), a delegate has to additionally provide an operator function setValue() with the following
parameters:
thisRef must be the same or a supertype of the property owner (for extension properties, it should be the type being
extended).
value must be of the same type as the property (or its supertype).
class Resource
class Owner {
var varResource: Resource by ResourceDelegate()
}
getValue() and/or setValue() functions can be provided either as member functions of the delegate class or extension
functions. The latter is handy when you need to delegate property to an object which doesn't originally provide these
functions. Both of the functions need to be marked with the operator keyword.
You can create delegates as anonymous objects without creating new classes using the interfaces ReadOnlyProperty and
ReadWriteProperty from the Kotlin standard library. They provide the required methods: getValue() is declared in
293
ReadOnlyProperty; ReadWriteProperty extends it and adds setValue(). Thus, you can pass a ReadWriteProperty whenever
a ReadOnlyProperty is expected.
Translation
rules
Under the hood for every delegated property the Kotlin compiler generates an auxiliary property and delegates to it. For
example, for the property prop the hidden property prop$delegate is generated, and the code of the accessors simply
delegates to this additional property:
class C {
var prop: Type by MyDelegate()
}
The Kotlin compiler provides all the necessary information about prop in the arguments: the first argument this refers to
an instance of the outer class C and this::prop is a reflection object of the KProperty type describing prop itself.
Providing
a
delegate
By defining the provideDelegate operator you can extend the logic of creating the object to which the property
implementation is delegated. If the object used on the right-hand side of by defines provideDelegate as a member or
extension function, that function will be called to create the property delegate instance.
One of the possible use cases of provideDelegate is to check the consistency of the property upon its initialization.
For example, if you want to check the property name before binding, you can write something like this:
294
operator fun provideDelegate(
thisRef: MyUI,
prop: KProperty<*>
): ReadOnlyProperty<MyUI, T> {
checkProperty(thisRef, prop.name)
// create delegate
return ResourceDelegate()
}
class MyUI {
fun <T> bindResource(id: ResourceID<T>): ResourceLoader<T> { ... }
thisRef must be the same or a supertype of the property owner (for extension properties, it should be the type being
extended);
The provideDelegate method is called for each property during the creation of the MyUI instance, and it performs the
necessary validation right away.
Without this ability to intercept the binding between the property and its delegate, to achieve the same functionality you'd
have to pass the property name explicitly, which isn't very convenient:
In the generated code, the provideDelegate method is called to initialize the auxiliary prop$delegate property. Compare
the generated code for the property declaration val prop: Type by MyDelegate() with the generated code above (when the
provideDelegate method is not present):
class C {
var prop: Type by MyDelegate()
}
295
// when the 'provideDelegate' function is available:
class C {
// calling "provideDelegate" to create the additional "delegate" property
private val prop$delegate = MyDelegate().provideDelegate(this, this::prop)
var prop: Type
get() = prop$delegate.getValue(this, this::prop)
set(value: Type) = prop$delegate.setValue(this, this::prop, value)
}
Note that the provideDelegate method affects only the creation of the auxiliary property and doesn't affect the code
generated for getter or setter.
With the PropertyDelegateProvider interface from the standard library, you can create delegate providers without creating
new classes.
Type
aliases
Type aliases provide alternative names for existing types. If the type name is too long you can introduce a different
shorter name and use the new one instead.
It's useful to shorten long generic types. For instance, it's often tempting to shrink collection types:
You can have new names for inner and nested classes:
class A {
inner class Inner
}
class B {
inner class Inner
}
296
Type aliases do not introduce new types. They are equivalent to the corresponding underlying types. When you add
typealias Predicate<T> and use Predicate<Int> in your code, the Kotlin compiler always expands it to (Int) -> Boolean.
Thus you can pass a variable of your type whenever a general function type is required and vice versa:
fun main() {
val f: (Int) -> Boolean = { it > 0 }
println(foo(f)) // prints "true"
Functions
Kotlin functions are declared using the fun keyword:
Function
usage
Functions are called using the standard approach:
Parameters
Function parameters are defined using Pascal notation - name: type. Parameters are separated using commas, and each
parameter must be explicitly typed:
You can use a trailing comma when you declare function parameters:
fun powerOf(
297
number: Int,
exponent: Int, // trailing comma
) { /*...*/ }
Default
arguments
Function parameters can have default values, which are used when you skip the corresponding argument. This reduces
the number of overloads:
fun read(
b: ByteArray,
off: Int = 0,
len: Int = b.size,
) { /*...*/ }
Overriding methods always use the same default parameter values as the base method. When overriding a method that
has default parameter values, the default parameter values must be omitted from the signature:
open class A {
open fun foo(i: Int = 10) { /*...*/ }
}
class B : A() {
override fun foo(i: Int) { /*...*/ } // No default value is allowed.
}
If a default parameter precedes a parameter with no default value, the default value can only be used by calling the
function with named arguments:
fun foo(
bar: Int = 0,
baz: Int,
) { /*...*/ }
If the last argument after default parameters is a lambda, you can pass it either as a named argument or outside the
parentheses:
fun foo(
bar: Int = 0,
baz: Int = 1,
qux: () -> Unit,
) { /*...*/ }
298
Named
arguments
When calling a function, you can name one or more of its arguments. This can be helpful when a function has many
arguments and it's difficult to associate a value with an argument, especially if it's a boolean or null value.
When you use named arguments in a function call, you can freely change the order they are listed in, and if you want to
use their default values, you can just leave these arguments out altogether.
Consider the following function, reformat(), which has 4 arguments with default values.
fun reformat(
str: String,
normalizeCase: Boolean = true,
upperCaseFirstLetter: Boolean = true,
divideByCamelHumps: Boolean = false,
wordSeparator: Char = ' ',
) { /*...*/ }
When calling this function, you don’t have to name all its arguments:
reformat(
"String!",
false,
upperCaseFirstLetter = false,
divideByCamelHumps = true,
'_'
)
You are also able to skip specific arguments with default values, rather than omitting them all. However, after the first
skipped argument, you must name all subsequent arguments:
You can pass a variable number of arguments ( vararg) with names using the spread operator:
On the JVM: You can't use the named argument syntax when calling Java functions because Java bytecode
does not always preserve the names of function parameters.
299
Unit-returning
functions
If a function does not return a useful value, its return type is Unit. Unit is a type with only one value - Unit. This value does
not have to be returned explicitly:
The Unit return type declaration is also optional. The above code is equivalent to:
Single-expression
functions
When a function returns a single expression, the curly braces can be omitted and the body is specified after a = symbol:
Explicitly declaring the return type is optional when this can be inferred by the compiler:
Explicit
return
types
Functions with block body must always specify return types explicitly, unless it's intended for them to return Unit, in
which case specifying the return type is optional.
Kotlin does not infer return types for functions with block bodies because such functions may have complex control flow
in the body, and the return type will be non-obvious to the reader (and sometimes even for the compiler).
Variable
number
of
arguments
(varargs)
You can mark a parameter of a function (usually the last one) with the vararg modifier:
In this case, you can pass a variable number of arguments to the function:
300
val list = asList(1, 2, 3)
Inside a function, a vararg -parameter of type T is visible as an array of T, as in the example above, where the ts variable
has type Array<out T>.
Only one parameter can be marked as vararg. If a vararg parameter is not the last one in the list, values for the
subsequent parameters can be passed using named argument syntax, or, if the parameter has a function type, by passing
a lambda outside the parentheses.
When you call a vararg -function, you can pass arguments individually, for example asList(1, 2, 3). If you already have an
array and want to pass its contents to the function, use the spread operator (prefix the array with *):
val a = arrayOf(1, 2, 3)
val list = asList(-1, 0, *a, 4)
Infix
notation
Functions marked with the infix keyword can also be called using the infix notation (omitting the dot and the parentheses
for the call). Infix functions must meet the following requirements:
The parameter must not accept variable number of arguments and must have no default value.
// is the same as
1.shl(2)
301
Infix function calls have lower precedence than arithmetic operators, type casts, and the rangeTo operator. The
following expressions are equivalent:
On the other hand, an infix function call's precedence is higher than that of the boolean operators && and ||, is-
and in -checks, and some other operators. These expressions are equivalent as well:
Note that infix functions always require both the receiver and the parameter to be specified. When you're calling a method
on the current receiver using the infix notation, use this explicitly. This is required to ensure unambiguous parsing.
class MyStringCollection {
infix fun add(s: String) { /*...*/ }
fun build() {
this add "abc" // Correct
add("abc") // Correct
//add "abc" // Incorrect: the receiver must be specified
}
}
Function
scope
Kotlin functions can be declared at the top level in a file, meaning you do not need to create a class to hold a function,
which you are required to do in languages such as Java, C#, and Scala. In addition to top level functions, Kotlin functions
can also be declared locally as member functions and extension functions.
Local
functions
Kotlin supports local functions, which are functions inside other functions:
dfs(graph.vertices[0], HashSet())
}
302
A local function can access local variables of outer functions (the closure). In the case above, visited can be a local
variable:
dfs(graph.vertices[0])
}
Member
functions
A member function is a function that is defined inside a class or object:
class Sample {
fun foo() { print("Foo") }
}
For more information on classes and overriding members see Classes and Inheritance.
Generic
functions
Functions can have generic parameters, which are specified using angle brackets before the function name:
Tail
recursive
functions
Kotlin supports a style of functional programming known as tail recursion. For some algorithms that would normally use
loops, you can use a recursive function instead without the risk of stack overflow. When a function is marked with the
tailrec modifier and meets the required formal conditions, the compiler optimizes out the recursion, leaving behind a fast
and efficient loop based version instead:
303
val eps = 1E-10 // "good enough", could be 10^-15
This code calculates the fixpoint of cosine, which is a mathematical constant. It simply calls Math.cos repeatedly starting
at 1.0 until the result no longer changes, yielding a result of 0.7390851332151611 for the specified eps precision. The
resulting code is equivalent to this more traditional style:
To be eligible for the tailrec modifier, a function must call itself as the last operation it performs. You cannot use tail
recursion when there is more code after the recursive call, and you cannot use it within try/ catch/ finally blocks. Currently,
tail recursion is supported by Kotlin for the JVM and Kotlin/Native.
See also:
Inline functions
Extension functions
High-order
functions
and
lambdas
Kotlin functions are first-class, which means they can be stored in variables and data structures, and can be passed as
arguments to and returned from other higher-order functions. You can perform any operations on functions that are
possible for other non-function values.
To facilitate this, Kotlin, as a statically typed programming language, uses a family of function types to represent
functions, and provides a set of specialized language constructs, such as lambda expressions.
Higher-order
functions
A higher-order function is a function that takes functions as parameters, or returns a function.
A good example of a higher-order function is the functional programming idiom fold for collections. It takes an initial
accumulator value and a combining function and builds its return value by consecutively combining the current
304
accumulator value with each collection element, replacing the accumulator value each time:
In the code above, the combine parameter has the function type (R, T) -> R, so it accepts a function that takes two
arguments of types R and T and returns a value of type R. It is invoked inside the for loop, and the return value is then
assigned to accumulator.
To call fold, you need to pass an instance of the function type to it as an argument, and lambda expressions ( described in
more detail below) are widely used for this purpose at higher-order function call sites:
fun main() {
//sampleStart
val items = listOf(1, 2, 3, 4, 5)
// Lambdas are code blocks enclosed in curly braces.
items.fold(0, {
// When a lambda has parameters, they go first, followed by '->'
acc: Int, i: Int ->
print("acc = $acc, i = $i, ")
val result = acc + i
println("result = $result")
// The last expression in a lambda is considered the return value:
result
})
// Parameter types in a lambda are optional if they can be inferred:
val joinedToString = items.fold("Elements:", { acc, i -> acc + " " + i })
// Function references can also be used for higher-order function calls:
val product = items.fold(1, Int::times)
//sampleEnd
println("joinedToString = $joinedToString")
println("product = $product")
}
Function
types
Kotlin uses function types, such as (Int) -> String, for declarations that deal with functions: val onClick: () -> Unit = ....
These types have a special notation that corresponds to the signatures of the functions - their parameters and return
values:
All function types have a parenthesized list of parameter types and a return type: (A, B) -> C denotes a type that
305
represents functions that take two arguments of types A and B and return a value of type C. The list of parameter
types may be empty, as in () -> A. The Unit return type cannot be omitted.
Function types can optionally have an additional receiver type, which is specified before the dot in the notation: the
type A.(B) -> C represents functions that can be called on a receiver object A with a parameter B and return a value C.
Function literals with receiver are often used along with these types.
Suspending functions belong to a special kind of function type that have a suspend modifier in their notation, such as
suspend () -> Unit or suspend A.(B) -> C.
The function type notation can optionally include names for the function parameters: (x: Int, y: Int) -> Point. These names
can be used for documenting the meaning of the parameters.
To specify that a function type is nullable, use parentheses as follows: ((Int, Int) -> Int)?.
Function types can also be combined using parentheses: (Int) -> ((Int) -> Unit).
The arrow notation is right-associative, (Int) -> (Int) -> Unit is equivalent to the previous example, but not to ((Int)
-> (Int)) -> Unit.
You can also give a function type an alternative name by using a type alias:
Instantiating
a
function
type
There are several ways to obtain an instance of a function type:
Use a code block within a function literal, in one of the following forms:
Function literals with receiver can be used as values of function types with receiver.
a constructor: ::Regex
These include bound callable references that point to a member of a particular instance: foo::toString.
306
class IntTransformer: (Int) -> Int {
override operator fun invoke(x: Int): Int = TODO()
}
The compiler can infer the function types for variables if there is enough information:
Non-literal values of function types with and without a receiver are interchangeable, so the receiver can stand in for the
first parameter, and vice versa. For instance, a value of type (A, B) -> C can be passed or assigned where a value of type
A.(B) -> C is expected, and the other way around:
fun main() {
//sampleStart
val repeatFun: String.(Int) -> String = { times -> this.repeat(times) }
val twoParameters: (String, Int) -> String = repeatFun // OK
fun runTransformation(f: (String, Int) -> String): String {
return f("hello", 3)
}
val result = runTransformation(repeatFun) // OK
//sampleEnd
println("result = $result")
}
A function type with no receiver is inferred by default, even if a variable is initialized with a reference to an
extension function. To alter that, specify the variable type explicitly.
Invoking
a
function
type
instance
A value of a function type can be invoked by using its invoke(...) operator: f.invoke(x) or just f(x).
If the value has a receiver type, the receiver object should be passed as the first argument. Another way to invoke a value
of a function type with receiver is to prepend it with the receiver object, as if the value were an extension function:
1.foo(2).
Example:
fun main() {
//sampleStart
val stringPlus: (String, String) -> String = String::plus
val intPlus: Int.(Int) -> Int = Int::plus
println(stringPlus.invoke("<-", "->"))
println(stringPlus("Hello, ", "world!"))
println(intPlus.invoke(1, 1))
307
println(intPlus(1, 2))
println(2.intPlus(3)) // extension-like call
//sampleEnd
}
Inline
functions
Sometimes it is beneficial to use inline functions, which provide flexible control flow, for higher-order functions.
Lambda
expressions
and
anonymous
functions
Lambda expressions and anonymous functions are function literals. Function literals are functions that are not declared
but are passed immediately as an expression. Consider the following example:
The function max is a higher-order function, as it takes a function value as its second argument. This second argument is
an expression that is itself a function, called a function literal, which is equivalent to the following named function:
Lambda
expression
syntax
The full syntactic form of lambda expressions is as follows:
Parameter declarations in the full syntactic form go inside curly braces and have optional type annotations.
If the inferred return type of the lambda is not Unit, the last (or possibly single) expression inside the lambda body is
treated as the return value.
If you leave all the optional annotations out, what's left looks like this:
Passing
trailing
lambdas
According to Kotlin convention, if the last parameter of a function is a function, then a lambda expression passed as the
corresponding argument can be placed outside the parentheses:
308
val product = items.fold(1) { acc, e -> acc * e }
If the lambda is the only argument in that call, the parentheses can be omitted entirely:
run { println("...") }
it:
implicit
name
of
a
single
parameter
It's very common for a lambda expression to have only one parameter.
If the compiler can parse the signature without any parameters, the parameter does not need to be declared and -> can
be omitted. The parameter will be implicitly declared under the name it:
Returning
a
value
from
a
lambda
expression
You can explicitly return a value from the lambda using the qualified return syntax. Otherwise, the value of the last
expression is implicitly returned.
ints.filter {
val shouldFilter = it > 0
shouldFilter
}
ints.filter {
val shouldFilter = it > 0
return@filter shouldFilter
}
This convention, along with passing a lambda expression outside of parentheses, allows for LINQ-style code:
Underscore
for
unused
variables
If the lambda parameter is unused, you can place an underscore instead of its name:
309
Destructuring
in
lambdas
Destructuring in lambdas is described as a part of destructuring declarations.
Anonymous
functions
The lambda expression syntax above is missing one thing – the ability to specify the function’s return type. In most
cases, this is unnecessary because the return type can be inferred automatically. However, if you do need to specify it
explicitly, you can use an alternative syntax: an anonymous function.
An anonymous function looks very much like a regular function declaration, except its name is omitted. Its body can be
either an expression (as shown above) or a block:
The parameters and the return type are specified in the same way as for regular functions, except the parameter types
can be omitted if they can be inferred from the context:
The return type inference for anonymous functions works just like for normal functions: the return type is inferred
automatically for anonymous functions with an expression body, but it has to be specified explicitly (or is assumed to be
Unit) for anonymous functions with a block body.
When passing anonymous functions as parameters, place them inside the parentheses. The shorthand syntax
that allows you to leave the function outside the parentheses works only for lambda expressions.
Another difference between lambda expressions and anonymous functions is the behavior of non-local returns. A return
statement without a label always returns from the function declared with the fun keyword. This means that a return inside
a lambda expression will return from the enclosing function, whereas a return inside an anonymous function will return
from the anonymous function itself.
Closures
A lambda expression or anonymous function (as well as a local function and an object expression) can access its closure,
which includes the variables declared in the outer scope. The variables captured in the closure can be modified in the
lambda:
var sum = 0
ints.filter { it > 0 }.forEach {
sum += it
310
}
print(sum)
Function
literals
with
receiver
Function types with receiver, such as A.(B) -> C, can be instantiated with a special form of function literals – function
literals with receiver.
As mentioned above, Kotlin provides the ability to call an instance of a function type with receiver while providing the
receiver object.
Inside the body of the function literal, the receiver object passed to a call becomes an implicit this, so that you can access
the members of that receiver object without any additional qualifiers, or access the receiver object using a this
expression.
This behavior is similar to that of extension functions, which also allow you to access the members of the receiver object
inside the function body.
Here is an example of a function literal with receiver along with its type, where plus is called on the receiver object:
The anonymous function syntax allows you to specify the receiver type of a function literal directly. This can be useful if
you need to declare a variable of a function type with receiver, and then to use it later.
Lambda expressions can be used as function literals with receiver when the receiver type can be inferred from the
context. One of the most important examples of their usage is type-safe builders:
class HTML {
fun body() { ... }
}
Inline
functions
Using higher-order functions imposes certain runtime penalties: each function is an object, and it captures a closure. A
311
closure means those variables that are accessed in the body of the function. Memory allocations (both for function
objects and classes) and virtual calls introduce runtime overhead.
But it appears that in many cases this kind of overhead can be eliminated by inlining the lambda expressions. The
functions shown below are good examples of this situation. The lock() function could be easily inlined at call-sites.
Consider the following case:
lock(l) { foo() }
Instead of creating a function object for the parameter and generating a call, the compiler could emit the following code:
l.lock()
try {
foo()
} finally {
l.unlock()
}
To make the compiler do this, you need to mark the lock() function with the inline modifier:
The inline modifier affects both the function itself and the lambdas passed to it: all of those will be inlined into the call site.
Inlining may cause the generated code to grow; however, if you do it in a reasonable way (avoiding inlining large
functions), it will pay off in performance, especially at "megamorphic" call-sites inside loops.
noinline
In case you want only some of the lambdas passed to an inline function to be inlined, you can mark some of your function
parameters with the noinline modifier:
inline fun foo(inlined: () -> Unit, noinline notInlined: () -> Unit) { ... }
Inlinable lambdas can only be called inside the inline functions or passed as inlinable arguments, but noinline ones can be
manipulated in any way you like such as stored in fields or passed around.
If an inline function has no inlinable function parameters and no reified type parameters, the compiler will issue
a warning, since inlining such functions is very unlikely to be beneficial (you can suppress the warning if you are
sure the inlining is needed using the annotation @Suppress("NOTHING_TO_INLINE")).
Non-local
returns
312
In Kotlin, you can only use a normal, unqualified return to exit a named function or an anonymous function. To exit a
lambda, use a label. A bare return is forbidden inside a lambda because a lambda cannot make the enclosing function
return:
But if the function the lambda is passed to is inlined, the return can be inlined as well. So it is allowed:
Such returns (located in a lambda, but exiting the enclosing function) are called non-local returns. This sort of construct
usually occurs in loops, which inline functions often enclose:
Note that some inline functions may call the lambdas passed to them as parameters not directly from the function body,
but from another execution context, such as a local object or a nested function. In such cases, non-local control flow is
also not allowed in the lambdas. To indicate that, the lambda parameter needs to be marked with the crossinline modifier:
313
}
break and continue are not yet available in inlined lambdas, but we are planning to support them too.
Reified
type
parameters
Sometimes you need to access a type passed as a parameter:
Here, you walk up a tree and use reflection to check if a node has a certain type. It’s all fine, but the call site is not
very pretty:
treeNode.findParentOfType(MyTreeNode::class.java)
What you actually want is simply pass a type to this function. You can call it like this:
treeNode.findParentOfType<MyTreeNode>()
To enable this, inline functions support reified type parameters, so you can write something like this:
You qualified the type parameter with the reified modifier to make it accessible inside the function, almost as if it were a
normal class. Since the function is inlined, no reflection is needed, normal operators like !is and as are working now. Also,
you can call it as mentioned above: myTree.findParentOfType<MyTreeNodeType>().
Though reflection may not be needed in many cases, you can still use it with a reified type parameter:
314
}
Normal functions (not marked as inline) cannot have reified parameters. A type that does not have a run-time
representation (for example, a non-reified type parameter or a fictitious type like Nothing) cannot be used as an argument
for a reified type parameter.
Inline
properties
The inline modifier can be used on accessors of properties that don't have a backing field. You can annotate individual
property accessors:
You can also annotate an entire property, which marks both of its accessors as inline:
At the call site, inline accessors are inlined as regular inline functions.
Restrictions
for
public
API
inline
functions
When an inline function is public or protected and is not a part of a private or internal declaration, it is considered a
module 's public API. It can be called in other modules and is inlined at such call sites as well.
This imposes certain risks of binary incompatibility caused by changes in the module that declares an inline function in
case the calling module is not re-compiled after the change.
To eliminate the risk of such incompatibility being introduced by a change in non -public API of a module, the public API
inline functions are not allowed to use non-public-API declarations, i.e. private and internal declarations and their parts, in
their bodies.
An internal declaration can be annotated with @PublishedApi, which allows its use in public API inline functions. When an
internal inline function is marked as @PublishedApi, its body is checked too, as if it were public.
Operator
overloading
Kotlin allows you to provide custom implementations for the predefined set of operators on types. These operators have
315
predefined symbolic representation (like + or *) and precedence. To implement an operator, provide a member function or
an extension function with a specific name for the corresponding type. This type becomes the left-hand side type for
binary operations and the argument type for the unary ones.
To overload an operator, mark the corresponding function with the operator modifier:
interface IndexedContainer {
operator fun get(index: Int)
}
Unary
operations
Unary
prefix
operators
Expression Translated to
+a a.unaryPlus()
-a a.unaryMinus()
!a a.not()
This table says that when the compiler processes, for example, an expression +a, it performs the following steps:
Looks up a function unaryPlus() with the operator modifier and no parameters for the receiver T, that means a member
function or an extension function.
If the function is present and its return type is R, the expression +a has type R.
These operations, as well as all the others, are optimized for basic types and do not introduce overhead of
function calls for them.
As an example, here's how you can overload the unary minus operator:
316
data class Point(val x: Int, val y: Int)
fun main() {
println(-point) // prints "Point(x=-10, y=-20)"
}
Increments
and
decrements
Expression Translated to
The inc() and dec() functions must return a value, which will be assigned to the variable on which the ++ or -- operation
was used. They shouldn't mutate the object on which the inc or dec was invoked.
The compiler performs the following steps for resolution of an operator in the postfix form, for example a++:
Looks up a function inc() with the operator modifier and no parameters, applicable to the receiver of type T.
For the prefix forms ++a and --a resolution works the same way, and the effect is:
Binary
operations
317
Arithmetic
operators
Expression Translated to
a + b a.plus(b)
a - b a.minus(b)
a * b a.times(b)
a / b a.div(b)
a % b a.rem(b)
a..b a.rangeTo(b)
For the operations in this table, the compiler just resolves the expression in the Translated to column.
Below is an example Counter class that starts at a given value and can be incremented using the overloaded + operator:
in
operator
Expression Translated to
a in b b.contains(a)
a !in b !b.contains(a)
For in and !in the procedure is the same, but the order of arguments is reversed.
Indexed
access
operator
Expression Translated to
a[i] a.get(i)
a[i, j] a.get(i, j)
318
Expression Translated to
a[i] = b a.set(i, b)
a[i, j] = b a.set(i, j, b)
Square brackets are translated to calls to get and set with appropriate numbers of arguments.
invoke
operator
Expression Translated to
a() a.invoke()
a(i) a.invoke(i)
a(i, j) a.invoke(i, j)
Augmented
assignments
Expression Translated to
a += b a.plusAssign(b)
a -= b a.minusAssign(b)
a *= b a.timesAssign(b)
a /= b a.divAssign(b)
a %= b a.remAssign(b)
For the assignment operations, for example a += b, the compiler performs the following steps:
319
If the corresponding binary function (that means plus() for plusAssign()) is available too, a is a mutable variable, and
the return type of plus is a subtype of the type of a, report an error (ambiguity).
Make sure its return type is Unit, and report an error otherwise.
Otherwise, try to generate code for a = a + b (this includes a type check: the type of a + b must be a subtype of a).
Equality
and
inequality
operators
Expression Translated to
These operators only work with the function equals(other: Any?): Boolean, which can be overridden to provide custom
equality check implementation. Any other function with the same name (like equals(other: Foo)) will not be called.
=== and !== (identity checks) are not overloadable, so no conventions exist for them.
The == operation is special: it is translated to a complex expression that screens for null 's. null == null is always true, and
x == null for a non-null x is always false and won't invoke x.equals().
Comparison
operators
Expression Translated to
All comparisons are translated into calls to compareTo, that is required to return Int.
320
Property
delegation
operators
provideDelegate, getValue and setValue operator functions are described in Delegated properties.
Infix
calls
for
named
functions
You can simulate custom infix operations by using infix function calls.
Type-safe
builders
By using well-named functions as builders in combination with function literals with receiver it is possible to create type-
safe, statically-typed builders in Kotlin.
Type-safe builders allow creating Kotlin-based domain-specific languages (DSLs) suitable for building complex
hierarchical data structures in a semi-declarative way. Sample use cases for the builders are:
fun result() =
html {
head {
title {+"XML encoding with Kotlin"}
}
body {
h1 {+"XML encoding with Kotlin"}
p {+"this format can be used as an alternative markup to XML"}
// mixed content
p {
+"This is some"
b {+"mixed"}
+"text. For more see the"
a(href = "https://kotlinlang.org") {+"Kotlin"}
+"project"
}
p {+"some text"}
// content generated by
p {
for (arg in args)
+arg
321
}
}
}
This is completely legitimate Kotlin code. You can play with this code online (modify it and run in the browser) here.
How
it
works
Assume that you need to implement a type-safe builder in Kotlin. First of all, define the model you want to build. In this
case you need to model HTML tags. It is easily done with a bunch of classes. For example, HTML is a class that
describes the <html> tag defining children like <head> and <body>. (See its declaration below.)
Now, let's recall why you can say something like this in the code:
html {
// ...
}
html is actually a function call that takes a lambda expression as an argument. This function is defined as follows:
This function takes one parameter named init, which is itself a function. The type of the function is HTML.() -> Unit, which
is a function type with receiver. This means that you need to pass an instance of type HTML (a receiver) to the function,
and you can call members of that instance inside the function.
html {
this.head { ... }
this.body { ... }
}
Now, this can be omitted, as usual, and you get something that looks very much like a builder already:
html {
head { ... }
body { ... }
}
So, what does this call do? Let's look at the body of html function as defined above. It creates a new instance of HTML,
then it initializes it by calling the function that is passed as an argument (in this example this boils down to calling head
322
and body on the HTML instance), and then it returns this instance. This is exactly what a builder should do.
The head and body functions in the HTML class are defined similarly to html. The only difference is that they add the built
instances to the children collection of the enclosing HTML instance:
Actually these two functions do just the same thing, so you can have a generic version, initTag:
And you can use them to build <head> and <body> tags.
One other thing to be discussed here is how you add text to tag bodies. In the example above you say something like:
html {
head {
title {+"XML encoding with Kotlin"}
}
// ...
}
So basically, you just put a string inside a tag body, but there is this little + in front of it, so it is a function call that invokes
a prefix unaryPlus() operation. That operation is actually defined by an extension function unaryPlus() that is a member of
the TagWithText abstract class (a parent of Title):
323
So, what the prefix + does here is wrapping a string into an instance of TextElement and adding it to the children
collection, so that it becomes a proper part of the tag tree.
All this is defined in a package com.example.html that is imported at the top of the builder example above. In the last
section you can read through the full definition of this package.
Scope
control:
@DslMarker
When using DSLs, one might have come across the problem that too many functions can be called in the context. You
can call methods of every available implicit receiver inside a lambda and therefore get an inconsistent result, like the tag
head inside another head:
html {
head {
head {} // should be forbidden
}
// ...
}
In this example only members of the nearest implicit receiver this@head must be available; head() is a member of the
outer receiver this@html, so it must be illegal to call it.
To make the compiler start controlling scopes you only have to annotate the types of all receivers used in the DSL with
the same marker annotation. For instance, for HTML Builders you declare an annotation @HTMLTagMarker:
@DslMarker
annotation class HtmlTagMarker
An annotation class is called a DSL marker if it is annotated with the @DslMarker annotation.
In our DSL all the tag classes extend the same superclass Tag. It's enough to annotate only the superclass with
@HtmlTagMarker and after that the Kotlin compiler will treat all the inherited classes as annotated:
@HtmlTagMarker
abstract class Tag(val name: String) { ... }
You don't have to annotate the HTML or Head classes with @HtmlTagMarker because their superclass is already
annotated:
html {
324
head {
head { } // error: a member of outer receiver
}
// ...
}
Note that it's still possible to call the members of the outer receiver, but to do that you have to specify this receiver
explicitly:
html {
head {
this@html.head { } // possible
}
// ...
}
Full
definition
of
the
com.example.html
package
This is how the package com.example.html is defined (only the elements used in the example above). It builds an HTML
tree. It makes heavy use of extension functions and lambdas with receiver.
package com.example.html
interface Element {
fun render(builder: StringBuilder, indent: String)
}
@DslMarker
annotation class HtmlTagMarker
@HtmlTagMarker
abstract class Tag(val name: String) : Element {
val children = arrayListOf<Element>()
val attributes = hashMapOf<String, String>()
325
private fun renderAttributes(): String {
val builder = StringBuilder()
for ((attr, value) in attributes) {
builder.append(" $attr=\"$value\"")
}
return builder.toString()
}
class A : BodyTag("a") {
var href: String
get() = attributes["href"]!!
set(value) {
attributes["href"] = value
}
}
326
}
Null
safety
Nullable
types
and
non-null
types
Kotlin's type system is aimed at eliminating the danger of null references, also known as The Billion Dollar Mistake.
One of the most common pitfalls in many programming languages, including Java, is that accessing a member of a null
reference will result in a null reference exception. In Java this would be the equivalent of a NullPointerException, or an
NPE for short.
A superclass constructor calls an open member whose implementation in the derived class uses an uninitialized
state.
Java interoperation:
Attempts to access a member of a null reference of a platform type;
Nullability issues with generic types being used for Java interoperation. For example, a piece of Java code might
add null into a Kotlin MutableList<String>, therefore requiring a MutableList<String?> for working with it.
In Kotlin, the type system distinguishes between references that can hold null (nullable references) and those that cannot
(non-null references). For example, a regular variable of type String cannot hold null:
fun main() {
//sampleStart
var a: String = "abc" // Regular initialization means non-null by default
a = null // compilation error
//sampleEnd
}
To allow nulls, you can declare a variable as a nullable string by writing String?:
fun main() {
//sampleStart
var b: String? = "abc" // can be set to null
327
b = null // ok
print(b)
//sampleEnd
}
Now, if you call a method or access a property on a, it's guaranteed not to cause an NPE, so you can safely say:
val l = a.length
But if you want to access the same property on b, that would not be safe, and the compiler reports an error:
But you still need to access that property, right? There are a few ways to do so.
Checking
for
null
in
conditions
First, you can explicitly check whether b is null, and handle the two options separately:
The compiler tracks the information about the check you performed, and allows the call to length inside the if. More
complex conditions are supported as well:
fun main() {
//sampleStart
val b: String? = "Kotlin"
if (b != null && b.length > 0) {
print("String of length ${b.length}")
} else {
print("Empty string")
}
//sampleEnd
}
Note that this only works where b is immutable (meaning it is a local variable that is not modified between the check and
its usage or it is a member val that has a backing field and is not overridable), because otherwise it could be the case that
b changes to null after the check.
Safe
calls
Your second option for accessing a property on a nullable variable is using the safe call operator ?.:
fun main() {
//sampleStart
328
val a = "Kotlin"
val b: String? = null
println(b?.length)
println(a?.length) // Unnecessary safe call
//sampleEnd
}
This returns b.length if b is not null, and null otherwise. The type of this expression is Int?.
Safe calls are useful in chains. For example, Bob is an employee who may be assigned to a department (or not). That
department may in turn have another employee as a department head. To obtain the name of Bob's department head (if
there is one), you write the following:
bob?.department?.head?.name
To perform a certain operation only for non-null values, you can use the safe call operator together with let:
fun main() {
//sampleStart
val listWithNulls: List<String?> = listOf("Kotlin", null)
for (item in listWithNulls) {
item?.let { println(it) } // prints Kotlin and ignores null
}
//sampleEnd
}
A safe call can also be placed on the left side of an assignment. Then, if one of the receivers in the safe calls chain is null,
the assignment is skipped and the expression on the right is not evaluated at all:
Elvis
operator
When you have a nullable reference, b, you can say "if b is not null, use it, otherwise use some non-null value":
Instead of writing the complete if expression, you can also express this with the Elvis operator ?::
val l = b?.length ?: -1
If the expression to the left of ?: is not null, the Elvis operator returns it, otherwise it returns the expression to the right.
Note that the expression on the right-hand side is evaluated only if the left-hand side is null.
329
Since throw and return are expressions in Kotlin, they can also be used on the right-hand side of the Elvis operator. This
can be handy, for example, when checking function arguments:
The
!!
operator
The third option is for NPE-lovers: the not-null assertion operator (!!) converts any value to a non-null type and throws an
exception if the value is null. You can write b!!, and this will return a non-null value of b (for example, a String in our
example) or throw an NPE if b is null:
val l = b!!.length
Thus, if you want an NPE, you can have it, but you have to ask for it explicitly and it won’t appear out of the blue.
Safe
casts
Regular casts may result in a ClassCastException if the object is not of the target type. Another option is to use safe casts
that return null if the attempt was not successful:
Collections
of
a
nullable
type
If you have a collection of elements of a nullable type and want to filter non-null elements, you can do so by using
filterNotNull:
Equality
In Kotlin there are two types of equality:
330
Referential equality (===- two references point to the same object)
Structural
equality
Structural equality is checked by the == operation and its negated counterpart !=. By convention, an expression like a ==
b is translated to:
If a is not null, it calls the equals(Any?) function, otherwise (a is null) it checks that b is referentially equal to null.
Note that there's no point in optimizing your code when comparing to null explicitly: a == null will be automatically
translated to a === null.
To provide a custom equals check implementation, override the equals(other: Any?): Boolean function. Functions with the
same name and other signatures, like equals(other: Foo), don't affect equality checks with the operators == and !=.
Structural equality has nothing to do with comparison defined by the Comparable<...> interface, so only a custom
equals(Any?) implementation may affect the behavior of the operator.
Referential
equality
Referential equality is checked by the === operation and its negated counterpart !==. a === b evaluates to true if and only
if a and b point to the same object. For values represented by primitive types at runtime (for example, Int), the ===
equality check is equivalent to the == check.
Floating-point
numbers
equality
When an equality check operands are statically known to be Float or Double (nullable or not), the check follows the IEEE
754 Standard for Floating-Point Arithmetic.
Otherwise, the structural equality is used, which disagrees with the standard so that NaN is equal to itself, and -0.0 is not
equal to 0.0.
This
expressions
To denote the current receiver, you use this expressions:
In an extension function or a function literal with receiver this denotes the receiver parameter that is passed on the left-
331
hand side of a dot.
If this has no qualifiers, it refers to the innermost enclosing scope. To refer to this in other scopes, label qualifiers are
used:
Qualified
this
To access this from an outer scope (a class, extension function, or labeled function literal with receiver) you write
this@label, where @label is a label on the scope this is meant to be from:
Implicit
this
When you call a member function on this, you can skip the this. part. If you have a non-member function with the same
name, use this with caution because in some cases it can be called instead:
fun main() {
//sampleStart
fun printLine() { println("Top-level function") }
class A {
fun printLine() { println("Member function") }
332
//sampleEnd()
}
Asynchronous
programming
techniques
For decades, as developers we are confronted with a problem to solve - how to prevent our applications from blocking.
Whether we're developing desktop, mobile, or even server-side applications, we want to avoid having the user wait or
what's worse cause bottlenecks that would prevent an application from scaling.
Threading
Callbacks
Reactive Extensions
Coroutines
Before explaining what coroutines are, let's briefly review some of the other solutions.
Threading
Threads are by far probably the most well-known approach to avoid applications from blocking.
Let's assume in the code above that preparePost is a long-running process and consequently would block the user
interface. What we can do is launch it in a separate thread. This would then allow us to avoid the UI from blocking. This is
a very common technique, but has a series of drawbacks:
Threads aren't cheap. Threads require context switches which are costly.
Threads aren't infinite. The number of threads that can be launched is limited by the underlying operating system. In
server-side applications, this could cause a major bottleneck.
Threads aren't always available. Some platforms, such as JavaScript do not even support threads.
333
Threads aren't easy. Debugging threads, avoiding race conditions are common problems we suffer in multi-threaded
programming.
Callbacks
With callbacks, the idea is to pass one function as a parameter to another function, and have this one invoked once the
process has completed.
This in principle feels like a much more elegant solution, but once again has several issues:
Difficulty of nested callbacks. Usually a function that is used as a callback, often ends up needing its own callback.
This leads to a series of nested callbacks which lead to incomprehensible code. The pattern is often referred to as the
titled christmas tree (braces represent branches of the tree).
Error handling is complicated. The nesting model makes error handling and propagation of these somewhat more
complicated.
Callbacks are quite common in event-loop architectures such as JavaScript, but even there, generally people have moved
away to using other approaches such as promises or reactive extensions.
Futures,
promises,
and
others
The idea behind futures or promises (there are also other terms these can be referred to depending on
language/platform), is that when we make a call, we're promised that at some point it will return with an object called a
Promise, which can then be operated on.
334
fun preparePostAsync(): Promise<Token> {
// makes request and returns a promise that is completed later
return promise
}
Different programming model. Similar to callbacks, the programming model moves away from a top-down imperative
approach to a compositional model with chained calls. Traditional program structures such as loops, exception
handling, etc. usually are no longer valid in this model.
Different APIs. Usually there's a need to learn a completely new API such as thenCompose or thenAccept, which can
also vary across platforms.
Specific return type. The return type moves away from the actual data that we need and instead returns a new type
Promise which has to be introspected.
Error handling can be complicated. The propagation and chaining of errors aren't always straightforward.
Reactive
extensions
Reactive Extensions (Rx) were introduced to C# by Erik Meijer. While it was definitely used on the .NET platform it really
didn't reach mainstream adoption until Netflix ported it over to Java, naming it RxJava. From then on, numerous ports
have been provided for a variety of platforms including JavaScript (RxJS).
The idea behind Rx is to move towards what's called observable streams whereby we now think of data as streams
(infinite amounts of data) and these streams can be observed. In practical terms, Rx is simply the Observer Pattern with a
series of extensions which allow us to operate on the data.
In approach it's quite similar to Futures, but one can think of a Future as returning a discrete element, whereas Rx returns
a stream. However, similar to the previous, it also introduces a complete new way of thinking about our programming
model, famously phrased as
Coroutines
Kotlin's approach to working with asynchronous code is using coroutines, which is the idea of suspendable
computations, i.e. the idea that a function can suspend its execution at some point and resume later on.
One of the benefits however of coroutines is that when it comes to the developer, writing non-blocking code is essentially
335
the same as writing blocking code. The programming model in itself doesn't really change.
This code will launch a long-running operation without blocking the main thread. The preparePost is what's called a
suspendable function, thus the keyword suspend prefixing it. What this means as stated above, is that the function will
execute, pause execution and resume at some point in time.
The function signature remains exactly the same. The only difference is suspend being added to it. The return type
however is the type we want to be returned.
The code is still written as if we were writing synchronous code, top-down, without the need of any special syntax,
beyond the use of a function called launch which essentially kicks off the coroutine (covered in other tutorials).
The programming model and APIs remain the same. We can continue to use loops, exception handling, etc. and
there's no need to learn a complete set of new APIs.
It is platform independent. Whether we're targeting JVM, JavaScript or any other platform, the code we write is the
same. Under the covers the compiler takes care of adapting it to each platform.
Coroutines are not a new concept, let alone invented by Kotlin. They've been around for decades and are popular in
some other programming languages such as Go. What is important to note though is that the way they're implemented in
Kotlin, most of the functionality is delegated to libraries. In fact, beyond the suspend keyword, no other keywords are
added to the language. This is somewhat different from languages such as C# that have async and await as part of the
syntax. With Kotlin, these are just library functions.
Coroutines
Asynchronous or non-blocking programming is an important part of the development landscape. When creating server-
side, desktop, or mobile applications, it's important to provide an experience that is not only fluid from the user's
perspective, but also scalable when needed.
Kotlin solves this problem in a flexible way by providing coroutine support at the language level and delegating most of
the functionality to libraries.
336
In addition to opening the doors to asynchronous programming, coroutines also provide a wealth of other possibilities,
such as concurrency and actors.
How
to
start
New to Kotlin? Take a look at the Getting started page.
Documentation
Coroutines guide
Basics
Channels
Asynchronous flow
Tutorials
Asynchronous programming techniques
Sample
projects
kotlinx.coroutines examples and sources
KotlinConf app
Annotations
Annotations are means of attaching metadata to code. To declare an annotation, put the annotation modifier in front of a
class:
337
Additional attributes of the annotation can be specified by annotating the annotation class with meta-annotations:
@Target specifies the possible kinds of elements which can be annotated with the annotation (such as classes,
functions, properties, and expressions);
@Retention specifies whether the annotation is stored in the compiled class files and whether it's visible through
reflection at runtime (by default, both are true);
@Repeatable allows using the same annotation on a single element multiple times;
@MustBeDocumented specifies that the annotation is part of the public API and should be included in the class or
method signature shown in the generated API documentation.
@Target(AnnotationTarget.CLASS, AnnotationTarget.FUNCTION,
AnnotationTarget.VALUE_PARAMETER, AnnotationTarget.EXPRESSION)
@Retention(AnnotationRetention.SOURCE)
@MustBeDocumented
annotation class Fancy
Usage
If you need to annotate the primary constructor of a class, you need to add the constructor keyword to the constructor
declaration, and add the annotations before it:
class Foo {
var x: MyDependency? = null
@Inject set
}
Constructors
Annotations can have constructors that take parameters.
338
Allowed parameter types are:
Strings
Classes (Foo::class)
Enums
Other annotations
Annotation parameters cannot have nullable types, because the JVM does not support storing null as a value of an
annotation attribute.
If an annotation is used as a parameter of another annotation, its name is not prefixed with the @ character:
If you need to specify a class as an argument of an annotation, use a Kotlin class ( KClass). The Kotlin compiler will
automatically convert it to a Java class, so that the Java code can access the annotations and arguments normally.
import kotlin.reflect.KClass
Lambdas
Annotations can also be used on lambdas. They will be applied to the invoke() method into which the body of the lambda
is generated. This is useful for frameworks like Quasar, which uses annotations for concurrency control.
339
Annotation
use-site
targets
When you're annotating a property or a primary constructor parameter, there are multiple Java elements which are
generated from the corresponding Kotlin element, and therefore multiple possible locations for the annotation in the
generated Java bytecode. To specify how exactly the annotation should be generated, use the following syntax:
The same syntax can be used to annotate the entire file. To do this, put an annotation with the target file at the top level of
a file, before the package directive or before all imports if the file is in the default package:
@file:JvmName("Foo")
package org.jetbrains.demo
If you have multiple annotations with the same target, you can avoid repeating the target by adding brackets after the
target and putting all the annotations inside the brackets:
class Example {
@set:[Inject VisibleForTesting]
var collaborator: Collaborator
}
file
field
delegate (the field storing the delegate instance for a delegated property)
To annotate the receiver parameter of an extension function, use the following syntax:
340
If you don't specify a use-site target, the target is chosen according to the @Target annotation of the annotation being
used. If there are multiple applicable targets, the first applicable target from the following list is used:
param
property
field
Java
annotations
Java annotations are 100% compatible with Kotlin:
import org.junit.Test
import org.junit.Assert.*
import org.junit.Rule
import org.junit.rules.*
class Tests {
// apply @Rule annotation to property getter
@get:Rule val tempFolder = TemporaryFolder()
Since the order of parameters for an annotation written in Java is not defined, you can't use a regular function call syntax
for passing the arguments. Instead, you need to use the named argument syntax:
// Java
public @interface Ann {
int intValue();
String stringValue();
}
// Kotlin
@Ann(intValue = 1, stringValue = "abc") class C
Just like in Java, a special case is the value parameter; its value can be specified without an explicit name:
// Java
public @interface AnnWithValue {
String value();
}
// Kotlin
@AnnWithValue("abc") class C
341
Arrays
as
annotation
parameters
If the value argument in Java has an array type, it becomes a vararg parameter in Kotlin:
// Java
public @interface AnnWithArrayValue {
String[] value();
}
// Kotlin
@AnnWithArrayValue("abc", "foo", "bar") class C
For other arguments that have an array type, you need to use the array literal syntax or arrayOf(...):
// Java
public @interface AnnWithArrayMethod {
String[] names();
}
Accessing
properties
of
an
annotation
instance
Values of an annotation instance are exposed as properties to Kotlin code:
// Java
public @interface Ann {
int value();
}
// Kotlin
fun foo(ann: Ann) {
val i = ann.value
}
Destructuring
declarations
Sometimes it is convenient to destructure an object into a number of variables, for example:
342
This syntax is called a destructuring declaration. A destructuring declaration creates multiple variables at once. You have
declared two new variables: name and age, and can use them independently:
println(name)
println(age)
The component1() and component2() functions are another example of the principle of conventions widely used in Kotlin
(see operators like + and *, for -loops as an example). Anything can be on the right-hand side of a destructuring
declaration, as long as the required number of component functions can be called on it. And, of course, there can be
component3() and component4() and so on.
The componentN() functions need to be marked with the operator keyword to allow using them in a
destructuring declaration.
Variables a and b get the values returned by component1() and component2() called on elements of the collection.
Example:
returning
two
values
from
a
function
Assume that you need to return two things from a function - for example, a result object and a status of some sort. A
compact way of doing this in Kotlin is to declare a data class and return its instance:
Since data classes automatically declare componentN() functions, destructuring declarations work here.
343
You could also use the standard class Pair and have function() return Pair<Int, Status>, but it's often better to
have your data named properly.
Example:
destructuring
declarations
and
maps
Probably the nicest way to traverse a map is this:
Present each of the elements as a pair by providing functions component1() and component2().
So you can freely use destructuring declarations in for -loops with maps (as well as collections of data class instances or
similar).
Underscore
for
unused
variables
If you don't need a variable in the destructuring declaration, you can place an underscore instead of its name:
The componentN() operator functions are not called for the components that are skipped in this way.
Destructuring
in
lambdas
You can use the destructuring declarations syntax for lambda parameters. If a lambda has a parameter of the Pair type (or
Map.Entry, or any other type that has the appropriate componentN functions), you can introduce several new parameters
instead of one by putting them in parentheses:
344
Note the difference between declaring two parameters and declaring a destructuring pair instead of a parameter:
If a component of the destructured parameter is unused, you can replace it with the underscore to avoid inventing its
name:
You can specify the type for the whole destructured parameter or for a specific component separately:
Reflection
Reflection is a set of language and library features that allows for introspecting the structure of your own program at
runtime. Kotlin makes functions and properties first-class citizens in the language, and introspecting them (for example,
learning a name or a type of a property or function at runtime) is closely intertwined with simply using a functional or
reactive style.
Kotlin/JS provides the limited support for reflection features. Learn more about reflection in Kotlin/JS.
JVM
dependency
On the JVM platform, the runtime component required for using the reflection features is distributed as a separate artifact
kotlin-reflect.jar in the Kotlin compiler distribution. This is done to reduce the required size of the runtime library for
applications that do not use reflection features.
In Gradle:
Kotlin
dependencies {
implementation("org.jetbrains.kotlin:kotlin-reflect:1.5.31")
}
345
Groovy
dependencies {
implementation "org.jetbrains.kotlin:kotlin-reflect:1.5.31"
}
In Maven:
<dependencies>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-reflect</artifactId>
</dependency>
</dependencies>
If you don't use Gradle or Maven, make sure you have kotlin-reflect.jar in the classpath of your project. In other supported
cases (IntelliJ IDEA projects, using command-line compiler or Ant), it is added by default. In command-line compiler and
Ant, you can use -no-reflect compiler option to exclude kotlin-reflect.jar from the classpath.
Class
references
The most basic reflection feature is getting the runtime reference to a Kotlin class. To obtain the reference to a statically
known Kotlin class, you can use the class literal syntax:
val c = MyClass::class
On JVM: a Kotlin class reference is not the same as a Java class reference. To obtain a Java class reference,
use the .java property on a KClass instance.
Bound
class
references
You can get the reference to a class of a specific object with the same ::class syntax by using the object as a receiver:
You obtain the reference to an exact class of an object, for instance GoodWidget or BadWidget, despite the type of the
receiver expression (Widget).
346
Callable
references
References to functions, properties, and constructors, apart from introspecting the program structure, can also be called
or used as instances of function types.
The common supertype for all callable references is KCallable<out R>, where R is the return value type, which is the
property type for properties, and the constructed type for constructors.
Function
references
When you have a named function declared like this:
You can call it directly (isOdd(5)). Alternatively, you can use it as a function type value: pass it to another function. To do
this, use the :: operator:
fun main() {
//sampleStart
val numbers = listOf(1, 2, 3)
println(numbers.filter(::isOdd))
//sampleEnd
}
Function references belong to one of the KFunction<out R> subtypes, depending on the parameter count, for example,
KFunction3<T1, T2, T3, R>.
:: can be used with overloaded functions when the expected type is known from the context. For example:
fun main() {
//sampleStart
fun isOdd(x: Int) = x % 2 != 0
fun isOdd(s: String) = s == "brillig" || s == "slithy" || s == "tove"
val numbers = listOf(1, 2, 3)
println(numbers.filter(::isOdd)) // refers to isOdd(x: Int)
//sampleEnd
}
Alternatively, you can provide the necessary context by storing the method reference in a variable with an explicitly
specified type:
If you need to use a member of a class, or an extension function, it needs to be qualified: String::toCharArray.
347
Note that even if you initialize a variable with a reference to an extension function, the inferred function type will have no
receiver (it will have an additional parameter accepting a receiver object). To have a function type with receiver instead,
specify the type explicitly:
fun <A, B, C> compose(f: (B) -> C, g: (A) -> B): (A) -> C {
return { x -> f(g(x)) }
}
It returns a composition of two functions passed to it: compose(f, g) = f(g(*)). Now, you can apply it to callable references:
fun <A, B, C> compose(f: (B) -> C, g: (A) -> B): (A) -> C {
return { x -> f(g(x)) }
}
fun main() {
//sampleStart
fun length(s: String) = s.length
val oddLength = compose(::isOdd, ::length)
val strings = listOf("a", "ab", "abc")
println(strings.filter(oddLength))
//sampleEnd
}
Property
references
To access properties as first-class objects in Kotlin, use the :: operator:
val x = 1
fun main() {
println(::x.get())
println(::x.name)
}
The expression ::x evaluates to a property object of type KProperty<Int>. You can read its value using get() or retrieve the
property name using the name property. For more information, see the docs on the KProperty class.
For a mutable property such as var y = 1, ::y returns a value of type KMutableProperty<Int>, which has a set() method:
348
var y = 1
fun main() {
::y.set(2)
println(y)
}
A property reference can be used where a function with a single generic parameter is expected:
fun main() {
//sampleStart
val strs = listOf("a", "bc", "def")
println(strs.map(String::length))
//sampleEnd
}
fun main() {
//sampleStart
class A(val p: Int)
val prop = A::p
println(prop.get(A(1)))
//sampleEnd
}
fun main() {
println(String::lastChar.get("abc"))
}
Interoperability
with
Java
reflection
On the JVM platform, standard library contains extensions for reflection classes that provide a mapping to and from Java
reflection objects (see package kotlin.reflect.jvm). For example, to find a backing field or a Java method that serves as a
getter for a Kotlin property, you can write something like this:
import kotlin.reflect.jvm.*
class A(val p: Int)
fun main() {
println(A::p.javaGetter) // prints "public final int A.getP()"
println(A::p.javaField) // prints "private final int A.p"
}
349
To get the Kotlin class corresponding to a Java class, use the .kotlin extension property:
Constructor
references
Constructors can be referenced just like methods and properties. You can use them wherever an object of function type
is expected that takes the same parameters as the constructor and returns an object of the appropriate type.
Constructors are referenced by using the :: operator and adding the class name. Consider the following function that
expects a function parameter with no parameters and return type Foo:
class Foo
Using ::Foo, the zero-argument constructor of the class Foo, you can call it like this:
function(::Foo)
Callable references to constructors are typed as one of the KFunction<out R> subtypes depending on the parameter
count.
Bound
function
and
property
references
You can refer to an instance method of a particular object:
fun main() {
//sampleStart
val numberRegex = "\\d+".toRegex()
println(numberRegex.matches("29"))
val isNumber = numberRegex::matches
println(isNumber("29"))
//sampleEnd
}
Instead of calling the method matches directly, the example uses a reference to it. Such reference is bound to its
receiver. It can be called directly (like in the example above) or used whenever an expression of function type is expected:
fun main() {
//sampleStart
val numberRegex = "\\d+".toRegex()
val strings = listOf("abc", "124", "a70")
println(strings.filter(numberRegex::matches))
//sampleEnd
}
350
Compare the types of bound and the corresponding unbound references. Bound callable reference has its receiver
"attached" to it, so the type of the receiver is no longer a parameter:
fun main() {
//sampleStart
val prop = "abc"::length
println(prop.get())
//sampleEnd
}
You don't need to specify this as the receiver: this::foo and ::foo are equivalent.
Bound
constructor
references
A bound callable reference to a constructor of an inner class can be obtained by providing an instance of the outer class:
class Outer {
inner class Inner
}
val o = Outer()
val boundInnerCtor = o::Inner
Kotlin
Multiplatform
Multiplatform projects are in Alpha. Language features and tooling may change in future Kotlin versions.
Support for multiplatform programming is one of Kotlin’s key benefits. It reduces time spent writing and maintaining
the same code for different platforms while retaining the flexibility and benefits of native programming. Learn more about
Kotlin Multiplatform benefits.
With Kotlin Multiplatform, share the code using the mechanisms Kotlin provides:
Share code among all platforms used in your project. Use it for sharing the common business logic that applies to all
platforms.
351
Code shared for all platforms
Share code among some platforms included in your project but not all. You can reuse much of the code in similar
platforms using a hierarchical structure. You can use target shortcuts for common combinations of targets or create
the hierarchical structure manually.
Hierarchical structure
If you need to access platform-specific APIs from the shared code, use the Kotlin mechanism of expected and actual
declarations.
352
Tutorials
Creating a multiplatform Kotlin library teaches how to create a multiplatform library available for JVM, JS, and Native
and which can be used from any other common code (for example, shared with Android and iOS). It also shows how to
write tests which will be executed on all platforms and use an efficient implementation provided by a specific platform.
Building a Full Stack Web App with Kotlin Multiplatform teaches the concepts behind building an application that
targets Kotlin/JVM and Kotlin/JS by building a client-server application that makes use of shared code, serialization,
and other multiplatform paradigms. It also provides a brief introduction to working with Ktor both as a server- and
client-side framework.
Getting
started
Get
familiar
with
KMM
Watch the introductory video, in which Kotlin Developer Advocate Ekaterina Petrova will explain what Kotlin Multiplatform
Mobile is and how you can use it in your project. Together with Ekaterina you'll set up an environment and prepare for
creating your first cross-platform mobile application with KMM.
Gif
Start
KMM
from
scratch
Set up your environment for KMM development.
353
Check the KMM sample projects for inspiration.
Make
an
Android
application
work
on
iOS
If you already have a mobile application and want to make it cross-platform:
Set
up
an
environment
for
KMM
development
Before you begin creating your first application to work on both iOS and Android, start by setting up an environment for
Kotlin Multiplatform Mobile (KMM) development:
1. If you are going to work with shared code or Android-specific code, you can work on any computer with an operating
system supported by Android Studio.
If you also want to write iOS-specific code and run an iOS application on a simulated or real device, use a Mac with a
macOS. These steps cannot be performed on other operating systems, such as Microsoft Windows. This is due to an
Apple requirement.
3. If you need to write iOS-specific code and run an iOS application, install Xcode – version 11.3 or higher.
Most of the time, Xcode will work in the background. You will use it to add Swift or Objective-C code to your iOS
application.
354
Kotlin Multiplatform Mobile plugin
355
Create
your
first
multiplatform
application
–
tutorial
Here you will learn how to create and run your first KMM application.
1. Set up your environment for KMM development by installing the necessary tools on a suitable operating system.
You will need a Mac with macOS to complete certain steps in this tutorial, which include writing iOS-specific
code and running an iOS application.
These steps cannot be performed on other operating systems, such as Microsoft Windows. This is due to an
Apple requirement.
You can also watch a video of this tutorial created by Ekaterina Petrova, Kotlin Developer Advocate.
Gif
3. Select KMM Application in the list of project templates, and click Next.
356
Mobile Multiplatform project template
357
Mobile Multiplatform project - general settings
Keep the default names for the application and shared folders.
Select Xcode build phases (packForXcode task) in the list of iOS framework distribution options.
358
Mobile Multiplatform project - additional settings
Now wait while your project is set up. It may take some time to download and set up the required components when you
do this for the first time.
To view the complete structure of your mobile multiplatform project, switch the view from Android to Project. You can
understand the KMM project structure and how you can use this.
359
Select the Project view
Run
your
application
You can run your multiplatform application on Android or iOS.
Run
your
application
on
Android
In the list of run configurations, select androidApp and then click Run.
360
361
First mobile multiplatform app on Android
Run
your
application
on
iOS
In the list of run configurations, select iosApp and then click Run.
362
363
First mobile multiplatform app on Android
2. Click the + button above the list of configurations and select iOS Application.
364
3. Name your configuration.
4. Select a simulated device in the Execution target list, and then click OK.
Run
tests
You can run tests to check that the shared code works correctly on both platforms. Of course, you can also write and run
tests to check the platform-specific code.
365
Run
tests
on
iOS
1. Open the file iosTest.kt in shared/src/iosTest/kotlin/com.example.kmmapplication.shared.
Directories with Test in their name contain tests.
This file includes a sample test for iOS.
Tests run on a simulator without UI. Congratulations! The test has passed – see test results in the console.
Run
tests
on
Android
For Android, follow a procedure that is very similar to the one for running tests on iOS.
Update
your
application
1. Open the file Greeting.kt in shared/src/commonMain/kotlin/com.example.kmmapplication.shared.
This directory stores the shared code for both platforms – Android and iOS. If you make changes to the shared code,
you will see changes in both applications.
366
Common Kotlin file
2. Update the shared code – use the Kotlin standard library function that works on all platforms and reverts text:
reversed().
class Greeting {
fun greeting(): String {
return "Guess what it is! > ${Platform().platform.reversed()}!"
}
}
367
368
Updated mobile multiplatform app on Android
369
Updated mobile multiplatform app on iOS
Next
steps
370
Once you've played with your first KMM application, you can:
Understand
the
KMM
project
structure
The purpose of the Kotlin Multiplatform Mobile (KMM) technology is unifying the development of applications with
common logic for Android and iOS platforms. To make this possible, KMM uses a mobile-specific structure of Kotlin
Multiplatform projects. This page describes the structure of a basic KMM project. Note that this structure isn’t the
only possible way to organize a KMM project; however, we recommend it as a starting point.
Shared module – a Kotlin module that contains common logic for both Android and iOS applications. Builds into an
Android library and an iOS framework. Uses Gradle as a build system.
Android application – a Kotlin module that builds into the Android application. Uses Gradle as a build system.
iOS application – an Xcode project that builds into the iOS application.
This is the structure of a KMM project that you create with a Project Wizard in IntelliJ IDEA or Android Studio. Real-life
371
projects can have more complex structure; we consider these three components essential for a KMM project.
Let’s take a closer look at the basic project and its components.
Root
project
The root project is a Gradle project that holds the shared module and the Android application as its subprojects. They are
linked together via the Gradle multi-project mechanism.
Kotlin
// settings.gradle.kts
include(":shared")
include(":androidApp")
Groovy
// settings.gradle
include ':shared'
include ':androidApp'
The iOS application is produced from an Xcode project. It’s stored in a separate directory within the root project.
Xcode uses its own build system; thus, the iOS application project isn’t connected with other parts of the KMM
project via Gradle. Instead, it uses the shared module as an external artifact – framework. For details on integration
between the shared module and the iOS application, see iOS application.
372
Basic KMM project directories
The root project does not hold source code. You can use it to store global configuration in its build.gradle(.kts) or
gradle.properties, for example, add repositories or define global configuration variables.
For more complex projects, you can add more modules into the root project by creating them in the IDE and linking via
include declarations in the Gradle settings.
Shared
module
Shared module contains the core application logic used in both target platforms: classes, functions, and so on. This is a
Kotlin Multiplatform module that compiles into an Android library and an iOS framework. It uses Gradle with the Kotlin
Multiplatform plugin applied and has targets for Android and iOS.
Kotlin
plugins {
kotlin("multiplatform") version "1.5.31"
// ..
}
kotlin {
android()
ios()
}
373
Groovy
plugins {
id 'org.jetbrains.kotlin.multiplatform' version '1.5.31'
//..
}
kotlin {
android()
ios()
}
Source
sets
The shared module contains the code that is common for Android and iOS applications. However, to implement the same
logic on Android and iOS, you sometimes need to write two platform-specific versions of it. To handle such cases, Kotlin
offers the expect/actual mechanism. The source code of the shared module is organized in three source sets accordingly:
commonMain stores the code that works on both platforms, including the expect declarations
Each source set has its own dependencies. Kotlin standard library is added automatically to all source sets, you don’t
need to declare it in the build script.
Kotlin
kotlin {
sourceSets {
val commonMain by getting
val androidMain by getting {
dependencies {
implementation("androidx.core:core-ktx:1.2.0")
}
}
val iosMain by getting
// ...
}
}
Groovy
kotlin {
sourceSets {
commonMain {
}
androidMain {
dependencies {
implementation 'androidx.core:core-ktx:1.2.0'
}
374
}
iosMain {
}
// ...
}
}
When you write your code, add the dependencies you need to the corresponding source sets. Read Multiplatform
documentation on adding dependencies for more information.
Along with *Main source sets, there are three matching test source sets:
commonTest
androidTest
iosTest
Use them to store unit tests for common and platform-specific source sets accordingly. By default, they have
dependencies on Kotlin test library, providing you with means for Kotlin unit testing: annotations, assertion functions and
other. You can add dependencies on other test libraries you need.
Kotlin
kotlin {
sourceSets {
// ...
val commonTest by getting {
dependencies {
implementation(kotlin("test-common"))
implementation(kotlin("test-annotations-common"))
}
}
val androidTest by getting
val iosTest by getting
}
Groovy
kotlin {
sourceSets {
//...
commonTest {
dependencies {
implementation kotlin('test-common')
implementation kotlin('test-annotations-common')
}
}
androidTest {
375
}
iosTest {
}
}
}
The main and test source sets described above are default. The Kotlin Multiplatform plugin generates them automatically
upon target creation. In your project, you can add more source sets for specific purposes. For more information, see
Multiplatform DSL reference.
Android
library
The configuration of the Android library produced from the shared module is typical for Android projects. To learn about
Android libraries creation, see Create an Android library in the Android developer documentation.
To produce the Android library, two more Gradle plugins are used in addition to Kotlin Multiplatform:
Android library
Kotlin
plugins {
// ...
id("com.android.library")
id("kotlin-android-extensions")
}
Groovy
plugins {
// ...
id 'com.android.library'
id 'kotlin-android-extensions'
}
The configuration of Android library is stored in the android {} top-level block of the shared module’s build script:
Kotlin
android {
compileSdkVersion(29)
defaultConfig {
minSdkVersion(24)
targetSdkVersion(29)
376
versionCode = 1
versionName = "1.0"
}
buildTypes {
getByName("release") {
isMinifyEnabled = false
}
}
}
Groovy
android {
compileSdkVersion 29
defaultConfig {
minSdkVersion 24
targetSdkVersion 29
versionCode 1
versionName '1.0'
}
buildTypes {
release {
minifyEnabled false
}
}
}
It’s typical for any Android project. You can edit it to suit your needs. To learn more, see the Android developer
documentation.
iOS
framework
For using in iOS applications, the shared module compiles into a framework – a kind of hierarchical directory with
shared resources used on the Apple platforms. This framework connects to the Xcode project that builds into an iOS
application.
The framework is produced via the Kotlin/Native compiler. The framework configuration is stored in the ios {} block of the
build script within kotlin {}. It defines the output type framework and the string identifier baseName that is used to form the
name of the output artifact. Its default value matches the Gradle module name. For a real project, it’s likely that
you’ll need a more complex configuration of the framework production. For details, see Multiplatform documentation.
Kotlin
kotlin {
// ...
ios {
binaries {
framework {
baseName = "shared"
}
}
377
}
}
Groovy
kotlin {
// ...
ios {
binaries {
framework {
baseName = 'shared'
}
}
}
}
Additionally, there is a Gradle task embedAndSignAppleFrameworkForXcode that exposes the framework to the Xcode
project from which the iOS application is built. It uses the configuration of the iOS application project to define the build
mode (debug or release) and provide the appropriate framework version to the specified location.
The task is built-in in the multiplatform plugin. It executes upon each build of the Xcode project to provide the latest
version of the framework for the iOS application. For details, see iOS application.
Android
application
The Android application part of a KMM project is a typical Android application written in Kotlin. In a basic KMM project, it
uses three Gradle plugins:
Kotlin Android
Android Application
Kotlin
plugins {
id("com.android.application")
kotlin("android")
id("kotlin-android-extensions")
}
Groovy
plugins {
id 'com.android.application'
id 'org.jetbrains.kotlin.android'
id 'kotlin-android-extensions'
378
}
To access the shared module code, the Android application uses it as a project dependency.
Kotlin
dependencies {
implementation(project(":shared"))
//..
}
Groovy
dependencies {
implementation project(':shared')
//..
}
Besides this dependency, the Android application uses the Kotlin standard library (which is added automatically) and
some common Android dependencies:
Kotlin
dependencies {
//..
implementation("androidx.core:core-ktx:1.2.0")
implementation("androidx.appcompat:appcompat:1.1.0")
implementation("androidx.constraintlayout:constraintlayout:1.1.3")
}
Groovy
dependencies {
//..
implementation 'androidx.core:core-ktx:1.2.0'
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
}
Add your project’s Android-specific dependencies to this block. The build configuration of the Android application is
located in the android {} top-level block of the build script:
Kotlin
379
android {
compileSdkVersion(29)
defaultConfig {
applicationId = "org.example.androidApp"
minSdkVersion(24)
targetSdkVersion(29)
versionCode = 1
versionName = "1.0"
}
buildTypes {
getByName("release") {
isMinifyEnabled = false
}
}
}
Groovy
android {
compileSdkVersion 29
defaultConfig {
applicationId 'org.example.androidApp'
minSdkVersion 24
targetSdkVersion 29
versionCode 1
versionName '1.0'
}
buildTypes {
'release' {
minifyEnabled false
}
}
}
It’s typical for any Android project. You can edit it to suit your needs. To learn more, see the Android developer
documentation.
iOS
application
The iOS application is produced from an Xcode project generated automatically by the Project Wizard. It resides in a
separate directory within the root KMM project.
380
Basic KMM Xcode project
For each build of the iOS application, the project obtains the latest version of the framework. To do this, it uses a Run
Script build phase that executes the embedAndSignAppleFrameworkForXcode Gradle task from the shared module. This
task generates the .framework with the needed configuration, depending on the Xcode environment settings, and puts the
artifact into the DerivedData Xcode directory.
381
Execution of embedAndSignAppleFrameworkForXcode in the Xcode project settings
To embed framework into the application and make the declarations from the shared module available in the source code
of the iOS application, the following build settings should be configured properly:
1. Other Linker flags under the Linking section: $(inherited) -framework shared
382
In other aspects, the Xcode part of a KMM project is a typical iOS application project. To learn more about creating iOS
application, see the Xcode documentation.
Make
your
Android
application
work
on
iOS
–
tutorial
Here you can learn how to make your existing Android application cross-platform so that it works both on Android and
iOS. You'll be able to write code and test it for both Android and iOS only once, in one place.
This tutorial uses a sample Android application with a single screen for entering a username and password. The
credentials are validated and saved to an in-memory database.
If you aren't familiar with KMM, you can learn how to create and configure a KMM application from scratch first.
Prepare
an
environment
for
development
1. Install Android Studio 4.2 or higher and other tools for KMM development on macOS.
You will need a Mac with macOS to complete certain steps in this tutorial, which include writing iOS-specific
code and running an iOS application.
These steps cannot be performed on other operating systems, such as Microsoft Windows. This is due to an
Apple requirement.
383
Project view
Make
your
code
cross-platform
To have a KMM application that works on iOS, you'll first make your code cross-platform, and then you’ll reuse your
cross-platform code in a new iOS application.
Decide
what
code
to
make
cross-platform
Decide which code of your Android application is better to share for iOS and which to keep native. A simple rule is: share
what you want to reuse as much as possible. The business logic is often the same for both Android and iOS, so it's a
great candidate for reuse.
384
In your sample Android application, the business logic is stored in the package
com.jetbrains.simplelogin.androidapp.data. Your future iOS application will use the same logic, so you should make it
cross-platform, as well.
Create
a
shared
module
for
cross-platform
code
The cross-platform code that is used for both iOS and Android is stored in the shared module. KMM provides a special
wizard for creating such modules.
In your Android project, create a KMM shared module for your cross-platform code. Later you'll connect it to your existing
Android application and your future iOS application.
385
1. In Android Studio, click File | New | New Module.
2. In the list of templates, select KMM Shared Module, enter the module name shared, and select the Regular framework
in the list of iOS framework distribution options.
This is required for connecting the shared module to the iOS application.
3. Click Finish.
The wizard will create the KMM shared module, update the configuration files, and create files with classes that
demonstrate the benefits of Kotlin Multiplatform. You can learn more about the KMM project structure.
Add
a
dependency
on
the
shared
module
to
your
Android
application
To use cross-platform code in your Android application, connect the shared module to it, move the business logic code
there, and make this code cross-platform.
1. Ensure that compileSdkVersion and minSdkVersion in build.gradle.kts of the shared module are the same as those in
the build.gradle of your Android application in the app module.
If they are different, update them in the build.gradle.kts of the shared module. Otherwise, you'll encounter a compile
error.
386
2. Add a dependency on the shared module to the build.gradle of your Android application.
dependencies {
implementation project(':shared')
}
4. To make sure that the shared module is successfully connected to your application, dump the greeting() function result
to the log by updating the onCreate() method of the LoginActivity class.
5. Search for Hello in the log, and you'll find the greeting from the shared module.
Make
the
business
logic
cross-platform
You can now extract the business logic code to the KMM shared module and make it platform-independent. This is
necessary for reusing the code for both Android and iOS.
1. Move the business logic code com.jetbrains.simplelogin.androidapp.data from the app directory to the
com.jetbrains.simplelogin.shared package in the shared/src/commonMain directory. You can drag and drop the
package or refactor it by moving everything from one directory to another.
387
Drag and drop the package with the business logic code
2. When Android Studio asks what you'd like to do, select to move the package, and then approve the refactoring.
388
Refactor the business logic package
389
Warnings about platform-dependent code
4. Remove Android-specific code by replacing it with cross-platform Kotlin code or connecting to Android-specific APIs
using expect and actual declarations. See the following sections for details.
1. In the login() function of the LoginDataSource class, replace IOException, which is not available in Kotlin, with
RuntimeException.
// Before
return Result.Error(IOException("Error logging in", e))
//After
return Result.Error(RuntimeException("Error logging in", e))
2. For email validation, replace the Patterns class from the android.utils package with a Kotlin regular expression
matching the pattern in the LoginDataValidator class:
// Before
private fun isEmailValid(email: String) = Patterns.EMAIL_ADDRESS.matcher(email).matches()
// After
private fun isEmailValid(email: String) = emailRegex.matches(email)
companion object {
private val emailRegex =
("[a-zA-Z0-9\\+\\.\\_\\%\\-\\+]{1,256}" +
"\\@" +
"[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}" +
"(" +
"\\." +
"[a-zA-Z0-9][a-zA-Z0-9\\-]{0,25}" +
")+").toRegex()
}
Since the Kotlin standard library doesn't provide functionality for generating UUIDs, you still need to use platform-specific
390
functionality for this case.
Provide the expect declaration for the randomUUID() function in the shared code and its actual implementations for each
platform – Android and iOS – in the corresponding source sets. You can learn more about connecting to platform-
specific APIs.
2. Create a Utils.kt file in the shared/src/commonMain directory and provide the expect declaration:
package com.jetbrains.simplelogin.shared
3. Create a Utils.kt file in the shared/src/androidMain directory and provide the actual implementation for randomUUID()
in Android:
package com.jetbrains.simplelogin.shared
import java.util.*
actual fun randomUUID() = UUID.randomUUID().toString()
4. Create a Utils.kt file in the shared/src/iosMain directory and provide the actual implementation for randomUUID() in
iOS:
package com.jetbrains.simplelogin.shared
import platform.Foundation.NSUUID
actual fun randomUUID(): String = NSUUID().UUIDString()
For Android and iOS, Kotlin will use different platform-specific implementations.
Run
your
cross-platform
application
on
Android
Run your cross-platform application for Android to make sure it works.
391
392
Android login application
Make
your
cross-platform
application
work
on
iOS
Once you've made your Android application cross-platform, you can create an iOS application and reuse the shared
business logic in it.
Create
an
iOS
project
in
Xcode
1. In Xcode, click File | New | Project.
393
iOS project template
394
iOS project settings
4. As the location for your project, select the directory that stores your cross-platform application, for example, kmm-
integrate-into-existing-app.
You can rename the simpleLoginIOS directory to iosApp for consistency with other top-level directories of your cross-
platform project.
395
Renamed iOS project directory in Android Studio
Connect
the
framework
to
your
iOS
project
Once you have the framework, you can connect it to your iOS project manually.
An alternative is to configure integration via Cocoapods, but that integration is beyond the scope of this tutorial.
1. In Xcode, open the iOS project settings by double-clicking the project name.
2. On the Build Phases tab of the project settings, click the + and add New Run Script Phase.
cd "$SRCROOT/.."
./gradlew :shared:embedAndSignAppleFrameworkForXcode
396
Add the script
4. Move the Run Script phase before the Compile Sources phase.
5. On the Build Settings tab, specify the Framework Search Path under Search Paths –
$(SRCROOT)/../shared/build/xcode-frameworks/$(CONFIGURATION)/$(SDK_NAME).
397
Framework search path
6. On the Build Settings tab, specify the Other Linker flags under Linking – $(inherited) -framework shared
398
Linker flag
7. Build the project in Xcode. If everything is set up correctly, the project will successfully build.
Use
the
shared
module
from
Swift
1. In Xcode, open the ContentView.swift file and import the shared module.
import shared
2. To check that it is properly connected, use the greeting() function from the KMM module:
import SwiftUI
import shared
399
400
Greeting from the KMM module
3. In ContentView.swift, write code for using data from the KMM module and rendering the application UI.
4. In simpleLoginIOSApp.swift, import the shared module and specify the arguments for the ContentView() function:
import SwiftUI
import shared
@main
struct SimpleLoginIOSApp: App {
var body: some Scene {
WindowGroup {
ContentView(viewModel: .init(loginRepository: LoginRepository(dataSource:
LoginDataSource()), loginValidator: LoginDataValidator()))
}
}
}
401
402
Simple login application
Enjoy
the
results
–
update
the
logic
only
once
Now your application is cross-platform. You can update the business logic in one place and see results on both Android
and iOS.
1. In Android Studio, change the validation logic for a user's password in the checkPassword() function of the
LoginDataValidator class:
package com.jetbrains.simplelogin.shared.data
class LoginDataValidator {
//...
fun checkPassword(password: String): Result {
return when {
password.length < 5 -> Result.Error("Password must be >5 characters")
password.toLowerCase() == "password" -> Result.Error("Password shouldn't be
\"password\"")
else -> Result.Success
}
}
//...
}
2. Update gradle.properties to connect your iOS application to Android Studio for running it on a simulated or real device
right there:
xcodeproj=iosApp/SimpleLoginIOS.xcodeproj
You will see the new run configuration simpleLoginIOS for running your iOS application right from Android Studio.
403
iOS run configuration
404
iOS application password error
405
406
Android application password error
What
else
to
share?
You've shared the business logic of your application, but you can also decide to share other layers of your application. For
example, the ViewModel class code is almost the same for Android and iOS applications, and you can share it if your
mobile applications should have the same presentation layer.
What's
next?
Use Ktor for networking
Connect
to
platform-specific
APIs
If you’re developing mobile applications for different platforms with Kotlin Multiplatform Mobile and need to access
platform-specific APIs that implement required functionality (for example, generating a UUID), you can use the Kotlin
mechanism of expected and actual declarations.
With this mechanism, a common module defines an expected declaration, and platform modules must provide actual
declarations that correspond to the expected one. This works for most Kotlin declarations, such as functions, classes,
interfaces, enums, properties, and annotations.
407
Expect/actual declarations in common and platform-specific modules
The compiler ensures that every declaration marked with the expect keyword in the common module has the
corresponding declarations marked with the actual keyword in all platform modules. The IDE provides tools that help you
create the missing actual declarations.
We recommend that you use expected and actual declarations only for Kotlin declarations that have platform-
specific dependencies. It is better to implement all possible functionality in the common module even if doing so
takes more time.
Don’t overuse expected and actual declarations – in some cases, an interface may be a better choice
because it is more flexible and easier to test.
Examples
For simplicity, the following examples use the intuitive target names iOS and Android. However, in your Gradle build files,
you need to use a specific target name from the list of supported targets.
Generate a UUID
408
Example:
Generate
a
UUID
Let's assume that you are developing iOS and Android applications using Kotlin Multiplatform Mobile and you want to
generate a universally unique identifier (UUID).
For this purpose, declare the expected function randomUUID() with the expect keyword in the common module. Don’t
include any implementation code.
//Common
expect fun randomUUID(): String
In each platform-specific module (iOS and Android), provide the actual implementation for the function randomUUID()
expected in the common module. Use the actual keyword to mark the actual implementation.
The following examples show the implementation of this for Android and iOS. Platform-specific code uses the actual
keyword and the expected name for the function.
//Android
import java.util.*
//iOS
import platform.Foundation.NSUUID
actual fun randomUUID(): String = NSUUID().UUIDString()
409
Example:
Send
and
receive
messages
from
a
WebSocket
Finally, let’s assume that you are developing a chat platform for iOS and Android using Kotlin Multiplatform Mobile.
Let's see how you can implement sending and receiving messages from a WebSocket.
For this purpose, define a common logic that you don’t need to duplicate in all platform modules – just add it once
to the common module. However, the actual implementation of the WebSocket class differs from platform to platform.
That’s why you should use expect/ actual declarations for this class.
In the common module, declare the expected class PlatformSocket() with the expect keyword. Don’t include any
implementation code.
//Common
internal expect class PlatformSocket(
url: String
) {
fun openSocket(listener: PlatformSocketListener)
fun closeSocket(code: Int, reason: String)
fun sendMessage(msg: String)
}
interface PlatformSocketListener {
fun onOpen()
fun onFailure(t: Throwable)
fun onMessage(msg: String)
fun onClosing(code: Int, reason: String)
fun onClosed(code: Int, reason: String)
}
In each platform-specific module (iOS and Android), provide the actual implementation for the class PlatformSocket()
expected in the common module. Use the actual keyword to mark the actual implementation.
The following examples show the implementation of this for Android and iOS.
//Android
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import okhttp3.WebSocket
410
override fun onClosed(webSocket: WebSocket, code: Int, reason: String) =
listener.onClosed(code, reason)
}
)
}
actual fun closeSocket(code: Int, reason: String) {
webSocket?.close(code, reason)
webSocket = null
}
actual fun sendMessage(msg: String) {
webSocket?.send(msg)
}
}
Android implementation uses the third-party library OkHttp. Add the corresponding dependency to build.gradle(.kts) in the
shared module:
Kotlin
sourceSets {
val androidMain by getting {
dependencies {
implementation("com.squareup.okhttp3:okhttp:$okhttp_version")
}
}
}
Groovy
commonMain {
dependencies {
implementation "com.squareup.okhttp3:okhttp:$okhttp_version"
}
}
iOS implementation uses NSURLSession from the standard Apple SDK and doesn't require additional dependencies.
//iOS
import platform.Foundation.*
import platform.darwin.NSObject
411
listener.onOpen()
}
override fun URLSession(
session: NSURLSession,
webSocketTask: NSURLSessionWebSocketTask,
didCloseWithCode: NSURLSessionWebSocketCloseCode,
reason: NSData?
) {
listener.onClosed(didCloseWithCode.toInt(), reason.toString())
}
},
delegateQueue = NSOperationQueue.currentQueue()
)
webSocket = urlSession.webSocketTaskWithURL(socketEndpoint)
listenMessages(listener)
webSocket?.resume()
}
private fun listenMessages(listener: PlatformSocketListener) {
webSocket?.receiveMessageWithCompletionHandler { message, nsError ->
when {
nsError != null -> {
listener.onFailure(Throwable(nsError.description))
}
message != null -> {
message.string?.let { listener.onMessage(it) }
}
}
listenMessages(listener)
}
}
actual fun closeSocket(code: Int, reason: String) {
webSocket?.cancelWithCloseCode(code.toLong(), null)
webSocket = null
}
actual fun sendMessage(msg: String) {
val message = NSURLSessionWebSocketMessage(msg)
webSocket?.sendMessage(message) { err ->
err?.let { println("send $msg error: $it") }
}
}
}
And here is the common logic in the common module that uses the platform-specific class PlatformSocket().
//Common
class AppSocket(url: String) {
private val ws = PlatformSocket(url)
var socketError: Throwable? = null
private set
var currentState: State = State.CLOSED
private set(value) {
field = value
stateListener?.invoke(value)
}
var stateListener: ((State) -> Unit)? = null
set(value) {
field = value
value?.invoke(currentState)
}
412
var messageListener: ((msg: String) -> Unit)? = null
fun connect() {
if (currentState != State.CLOSED) {
throw IllegalStateException("The socket is available.")
}
socketError = null
currentState = State.CONNECTING
ws.openSocket(socketListener)
}
fun disconnect() {
if (currentState != State.CLOSED) {
currentState = State.CLOSING
ws.closeSocket(1000, "The user has closed the connection.")
}
}
fun send(msg: String) {
if (currentState != State.CONNECTED) throw IllegalStateException("The connection is
lost.")
ws.sendMessage(msg)
}
private val socketListener = object : PlatformSocketListener {
override fun onOpen() {
currentState = State.CONNECTED
}
override fun onFailure(t: Throwable) {
socketError = t
currentState = State.CLOSED
}
override fun onMessage(msg: String) {
messageListener?.invoke(msg)
}
override fun onClosing(code: Int, reason: String) {
currentState = State.CLOSING
}
override fun onClosed(code: Int, reason: String) {
currentState = State.CLOSED
}
}
enum class State {
CONNECTING,
CONNECTED,
CLOSING,
CLOSED
}
}
Add
dependencies
to
KMM
modules
Every application requires a set of libraries in order to operate successfully. A KMM application can depend on
multiplatform libraries that work on both iOS and Android, and it can depend on platform-specific iOS and Android
libraries.
Multiplatform dependencies
413
iOS dependencies
Android dependencies
Multiplatform
libraries
You can add dependencies on libraries that have adopted Kotlin Multiplatform technology, such as kotlinx.coroutines and
SQLDelight. The authors of these libraries usually provide guides for adding their dependencies to your project.
When using a multiplatform library that does not have hierarchical structure support in a multiplatform project
that does, you won't be able to use IDE features, such as code completion and highlighting, for the shared iOS
source set.
This is a known issue, and we are working on resolving it. In the meantime, you can use this workaround.
Dependency
on
the
Kotlin
standard
library
The Kotlin standard library is added automatically to all multiplatform projects, you don’t have to do anything
manually.
Dependency
on
a
library
shared
for
all
source
sets
If you want to use a library from all source sets, you can add it only to the common source set. The Kotlin Multiplatform
Mobile plugin will add the corresponding parts to any other source sets automatically.
Kotlin
kotlin {
sourceSets["commonMain"].dependencies {
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.5.2")
}
sourceSets["androidMain"].dependencies {
414
//dependency to platform part of kotlinx.coroutines will be added automatically
}
}
Groovy
kotlin {
sourceSets {
commonMain {
dependencies {
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.5.2'
}
}
androidMain {
dependencies {
//dependency to platform part of kotlinx.coroutines will be added automatically
}
}
}
}
Dependency
on
a
library
used
in
specific
source
sets
If you want to use a multiplatform library just for specific source sets, you can add it exclusively to them. The specified
library declarations will then be available only in those source sets.
Don't use a platform-specific name in such cases, like SQLDelight native-driver in the example below. Find the
exact name in the library’s documentation.
Kotlin
kotlin {
sourceSets["commonMain"].dependencies {
//kotlinx.coroutines will be available in all source sets
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.5.2")
}
sourceSets["androidMain"].dependencies {
}
sourceSets["iosX64Main"].dependencies {
//SQLDelight will be available only in the iOS source set, but not in Android or common
implementation("com.squareup.sqldelight:native-driver:1.4.1)
}
}
Groovy
kotlin {
sourceSets {
commonMain {
dependencies {
415
// kotlinx.coroutines will be available in all source sets
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.5.2'
}
}
androidMain {
dependencies { }
}
iosMain {
dependencies {
// SQLDelight will be available only in the iOS source set, but not in Android or
common
implementation 'com.squareup.sqldelight:native-driver:1.4.1'
}
}
}
}
Dependency
on
another
multiplatform
project
You can connect one multiplatform project to another as a dependency. To do this, simply add a project dependency to
the source set that needs it. If you want to use a dependency in all source sets, add it to the common one. In this case,
other source sets will get their versions automatically.
Kotlin
kotlin {
sourceSets["commonMain"].dependencies {
implementation(project(":some-other-multiplatform-module"))
}
sourceSets["androidMain"].dependencies {
//platform part of :some-other-multiplatform-module will be added automatically
}
}
Groovy
kotlin {
sourceSets {
commonMain {
dependencies {
implementation project(':some-other-multiplatform-module')
}
}
androidMain {
dependencies {
//platform part of :some-other-multiplatform-module will be added automatically
}
}
}
}
416
iOS
dependencies
Apple SDK dependencies (such as Foundation or Core Bluetooth) are available as a set of prebuilt libraries in Kotlin
Multiplatform Mobile projects. They do not require any additional configuration.
You can also reuse other libraries and frameworks from the iOS ecosystem in your iOS source sets. Kotlin supports
interoperability with Objective-C dependencies and Swift dependencies if their APIs are exported to Objective-C with the
@objc attribute. Pure Swift dependencies are not yet supported.
Integration with the CocoaPods dependency manager is also supported with the same limitation – you cannot use pure
Swift pods.
We recommend using CocoaPods to handle iOS dependencies in Kotlin Multiplatform Mobile (KMM) projects. Manage
dependencies manually only if you want to tune the interop process specifically or if you have some other strong reason to
do so.
When using third-party iOS libraries in multiplatform projects with hierarchical structure support, for example
with the ios() target shortcut, you won't be able to use IDE features, such as code completion and highlighting,
for the shared iOS source set.
This is a known issue, and we are working on resolving it. In the meantime, you can use this workaround.
This issue doesn't apply to platform libraries supported out of the box.
With
CocoaPods
1. Perform initial CocoaPods integration setup
2. Add a dependency on a Pod library from the CocoaPods repository that you want to use by including pod() in the build
script of your project.
Kotlin
kotlin {
cocoapods {
//..
pod("AFNetworking") {
version = "~> 4.0.1"
}
}
}
Groovy
kotlin {
cocoapods {
//..
417
pod('AFNetworking') {
version = '~> 4.0.1'
}
}
}
To use the dependency in your Kotlin code, import the package cocoapods.<library-name>. In the example above, that
would be:
import cocoapods.AFNetworking.*
Without
CocoaPods
If you don’t want to use CocoaPods, you can use the cinterop tool to create Kotlin bindings for Objective-C or Swift
declarations. This will allow you to call them from Kotlin code. To do this:
The steps differ a bit for libraries and frameworks, but the idea remains the same.
2. Build a library (library authors usually provide a guide on how to do this) and get a path to the binaries.
4. Add a first string to this file: language = Objective-C. If you want to use a pure C dependency, omit the language
property.
package sets the name of the package these declarations should be put into.
For example:
headers = DateTools.h
418
package = DateTools
6. Add information about interoperability with this library to the build script:
Pass the path to the .def file. This path can be omitted if your .def file has the same name as cinterop and is placed
in the src/nativeInterop/cinterop/ directory.
Tell cinterop where to look for header files using the includeDirs option.
Kotlin
kotlin {
iosX64() {
compilations.getByName("main") {
val DateTools by cinterops.creating {
// Path to .def file
defFile("src/nativeInterop/cinterop/DateTools.def")
// Directories for header search (an analogue of the -I<path> compiler option)
includeDirs("include/this/directory", "path/to/another/directory")
}
val anotherInterop by cinterops.creating { /* ... */ }
}
binaries.all {
// Linker options required to link to the library.
linkerOpts("-L/path/to/library/binaries", "-lbinaryname")
}
}
}
Groovy
kotlin {
iosX64 {
compilations.main {
cinterops {
DateTools {
// Path to .def file
defFile("src/nativeInterop/cinterop/DateTools.def")
binaries.all {
// Linker options required to link to the library.
linkerOpts "-L/path/to/library/binaries", "-lbinaryname"
}
419
}
}
Now you can use this dependency in your Kotlin code. To do that, import the package you’ve set up in the package
property in the .def file. For the example above, this will be:
import DateTools.*
2. Build the framework (framework authors usually provide a guide on how to do this) and get a path to the binaries.
4. Add the first string to this file: language = Objective-C. If you want to use a pure C dependency, omit the language
property.
modules – the name of the framework that should be processed by the cinterop.
package – the name of the package these declarations should be put into. For example:
modules = MyFramework
package = MyFramework
6. Add information about interoperability with the framework to the build script:
Pass the path to the .def file. This path can be omitted if your .def file has the same name as the cinterop and is
placed in the src/nativeInterop/cinterop/ directory.
Pass the framework name to the compiler and linker using the -framework option. Pass the path to the framework
sources and binaries to the compiler and linker using the -F option.
Kotlin
kotlin {
iosX64() {
compilations.getByName("main") {
val DateTools by cinterops.creating {
// Path to .def file
defFile("src/nativeInterop/cinterop/DateTools.def")
420
val anotherInterop by cinterops.creating { /* ... */ }
}
binaries.all {
// Tell the linker where the framework is located.
linkerOpts("-framework", "MyFramework", "-F/path/to/framework/")
}
}
}
Groovy
kotlin {
iosX64 {
compilations.main {
cinterops {
DateTools {
// Path to .def file
defFile("src/nativeInterop/cinterop/MyFramework.def")
binaries.all {
// Tell the linker where the framework is located.
linkerOpts("-framework", "MyFramework", "-F/path/to/framework/")
}
}
}
Now you can use this dependency in your Kotlin code. To do this, import the package you’ve set up in the package
property in the .def file. For the example above, this will be:
import MyFramework.*
Learn more about Objective-C and Swift interop and configuring cinterop from Gradle.
Workaround
to
enable
IDE
support
for
the
shared
iOS
source
set
Due to a known issue, you won't be able to use IDE features, such as code completion and highlighting, for the shared
iOS source set in a multiplatform project with hierarchical structure support if your project depends on:
Third-party iOS libraries, with the exception of platform libraries supported out of the box.
This issue applies only to the shared iOS source set. The IDE will correctly support the rest of the code.
421
All projects created with the KMM Project Wizard support the hierarchical structure, which means this issue
affects them.
To enable IDE support in these cases, you can work around the issue by adding the following code to build.gradle.(kts) in
the shared directory of your project:
Kotlin
iosTarget("ios")
Groovy
def iosTarget
if (System.getenv("SDK_NAME")?.startsWith("iphoneos")) {
iosTarget = kotlin.&iosArm64
} else {
iosTarget = kotlin.&iosX64
}
In this code sample, the configuration of iOS targets depends on the environment variable SDK_NAME, which is managed
by Xcode. For each build, you'll have only one iOS target, named ios, that uses the iosMain source set. There will be no
hierarchy of the iosMain, iosArm64, and iosX64 source sets.
This is a temporary workaround. If you are a library author, we recommend that you migrate to the hierarchical
structure as soon as possible.
With this workaround, Kotlin Multiplatform tooling analyzes your code against only the one native target that is
active during the current build. This might lead to various errors during the complete build with all targets, and
errors are more likely if your project contains other native targets in addition to the iOS ones.
Android
dependencies
The workflow for adding Android-specific dependencies to a KMM module is the same as it is for pure Android projects:
add a line to your Gradle build script declaring the dependency you need and import the project. You’ll then be able
to use this dependency in your Kotlin code.
We recommend adding Android dependencies to KMM projects by adding them to a specific Android source set:
422
Kotlin
sourceSets["androidMain"].dependencies {
implementation("com.example.android:app-magic:12.3")
}
Groovy
sourceSets {
androidMain {
dependencies {
implementation 'com.example.android:app-magic:12.3'
}
}
}
Moving what was a top-level dependency in an Android project to a specific source set in a KMM project might be
difficult if the top-level dependency had a non-trivial configuration name. For example, to move а debugImplementation
dependency from the top level of an Android project, you’ll need to add an implementation dependency to the source
set named androidDebug. To minimize the effort you have to put in to deal with migration problems like this, you can add
a dependencies block inside the android block:
Kotlin
android {
...
dependencies {
implementation("com.example.android:app-magic:12.3")
}
}
Groovy
android {
...
dependencies {
implementation 'com.example.android:app-magic:12.3'
}
}
Dependencies declared here will be treated exactly the same as dependencies from the top-level block, but declaring
them this way will also separate Android dependencies visually in your build script and make it less confusing.
Putting dependencies into a standalone dependencies block at the end of the script, in a way that is idiomatic to Android
projects, is also supported. However, we strongly recommend against doing this because configuring a build script with
423
Android dependencies in the top-level block and other target dependencies in each source set is likely to cause
confusion.
Configure
SQLDelight
for
data
storage
In the world of mobile development, databases are often used for local data storage on client devices. One of the options
for working with databases in Kotlin Mobile Multiplatform (KMM) projects is the SQLDelight library. It generates type-safe
Kotlin APIs from SQL statements for various relational databases. SQLDelight also provides a multiplatform
implementation of the SQLite driver. For a description of SQLDelight features and other details, see the SQLDelight
documentation.
In this article, we’ll show how to start using databases in your KMM project with SQLDelight:
Connect
and
configure
SQLDelight
Gradle
plugin
To connect the SQLDelight plugin to a project, apply the SQLDelight Gradle plugin in your project’s build script (root
build.gradle or build.gradle.kts): First, add the plugin's classpath to the build system:
Kotlin
buildscript {
repositories {
google()
mavenCentral()
}
dependencies {
classpath("com.squareup.sqldelight:gradle-plugin:$sql_delight_version")
}
}
Groovy
buildscript {
repositories {
google()
mavenCentral()
424
}
dependencies {
classpath "com.squareup.sqldelight:gradle-plugin:$sql_delight_version"
}
}
Instead of $sql_delight_version, use the version you need for your project.
Then apply the SQLDelight Gradle plugin by adding this line at the beginning of the build script (build.gradle or
build.gradle.kts) in your shared multiplatform module:
Kotlin
plugins {
id("com.squareup.sqldelight")
}
Groovy
Database
drivers
Kotlin
Groovy
commonMain {
dependencies {
implementation "com.squareup.sqldelight:runtime:$sql_delight_version"
}
}
425
To connect the SQLite database driver for Android, add the following to the dependencies block of the corresponding
source set in the module's build.gradle or build.gradle.kts:
Kotlin
Groovy
androidMain {
dependencies {
implementation "com.squareup.sqldelight:android-driver:$sql_delight_version"
}
}
Kotlin
Groovy
iosMain {
dependencies {
implementation "com.squareup.sqldelight:native-driver:$sql_delight_version"
}
}
Configuration
To configure the SQLDelight API generator, use the sqldelight top-level block of the build script. For example, to create a
database named AppDatabase and specify the package name com.example.db for the generated Kotlin classes, use this
configuration block:
Kotlin
426
sqldelight {
database("AppDatabase") {
packageName = "com.example.db"
}
}
Groovy
sqldelight {
AppDatabase {
packageName = "com.example.db"
}
}
This SQLDelight configuration will be used for all the code examples listed below.
To learn what you can configure in SQLDelight and how to do it, see the SQLDelight documentation.
Create
an
SQLite
driver
SQLDelight provides multiple platform-specific implementations of the SQLite driver, so you should create it for each
platform separately. In the common code, you can refer to these drivers using the common SqlDriver interface.
Android
driver
On Android, the SQLite driver is implemented by the AndroidSqliteDriver class. When you create its instance, pass the
database information and the link to context to the constructor. For example, this code creates an SQLite driver for a
database named AppDatabase:
iOS
driver
On iOS, the SQLite driver implementation is the NativeSqliteDriver class:
427
actual class DatabaseDriverFactory {
actual fun createDriver(): SqlDriver {
return NativeSqliteDriver(AppDatabase.Schema, "test.db")
}
}
Now you can create the DatabaseDriverFactory instance in your applications' code and pass it to the common module.
Then create an AppDatabase instance to perform database operations:
See the Networking & Data Storage Hands-on for the full example.
Table
operations
The SQLDelight generator works as follows: you create a file with the .sq extension in which you provide all the required
SQL queries to the database. The SQLDelight plugin generates the Kotlin code for execution of these queries. This way,
SQLDelight automatically implements the interaction of your app with the database. This eliminates the need for manual
implementation of entity classes and code that maps Kotlin classes onto a relational database model.
The syntax of the SQLDelight generator lets you implement all the basic SQLite commands, including cascading, indexes,
triggers, and others.
Create
Typically, queries for creating all the necessary database tables are listed at the beginning of the .sq file. To create a
table, use the SQL command CREATE TABLE. For example, this query creates a table with two fields:
For this query, SQLDelight generates the Language Kotlin interface with the specified fields. It will be used in functions
that implement operations with the Language table.
Delete
SQL's DELETE operator is used to delete rows from database tables. For example, to delete all records from the table,
declare the following query in the .sq file:
deleteAllLanguages:
DELETE FROM Language;
428
The label deleteAllLanguages: in the first line declares the name for the Kotlin function that will execute this query.
fun deleteAllLanguages()
To execute the deleteAllLanguages query from your code, write the following:
fun deleteAllLanguages() {
appDatabaseQueries.deleteAllLanguages()
}
You can use the WHERE operator to delete certain rows from a table, for example:
deleteLanguageById:
DELETE FROM Language
WHERE id = ?;
To delete a specific database record with the deleteLanguageById() function, call it on the AppDatabaseQueries object
and pass the id of the record to be deleted:
Insert
To add a data record into a table, use the SQL command INSERT. A query for inserting entries into the Language table
may look like this:
insertLanguage:
INSERT INTO Language(id, name)
VALUES(?, ?);
insertLanguage: here defines the name of the corresponding Kotlin function that SQLDelight generates:
The function takes two arguments that match the table fields specified in the query.
This is how you insert a new record into the table in your app’s code:
429
data class SystemLanguage(
val id: Long,
val name: String
)
Update
The SQL command UPDATE changes the values of given fields of specific rows within tables. For example, this query
changes the name of the record with the provided identifier:
updateLanguageName:
UPDATE Language
SET name = ?
WHERE id = ?;
updateLanguageName: here defines the name of the corresponding Kotlin function that SQLDelight generates:
This is how you update a record in the table in your app’s code:
Select
To select records from tables, use the SELECT operator. For example, if you want to select all the records from a table,
add the following query in the .sq file:
selectAllLanguages:
SELECT * FROM Language;
430
For this SQL query, SQlDelight will create the following functions:
As you can see, the first argument in the second selectAllLanguages function is the mapper lambda that converts data
from the selection into objects of an arbitrary type T. For example, if you need to transform the query results into entities
required for the app's business logic, write the following code:
Most queries include selection conditions.If you want to display a record with a specific identifier, add the following
request in the .sq file:
selectLanguageById:
SELECT * FROM Language
WHERE id = ?;
Similar to the above example, you can create a function that will query the database and convert the result to an object of
the required data class:
Transactions
SQLDelight allows multiple SQL queries to be executed in a single transaction. For this purpose, the generated Kotlin
431
interface with queries provides the transaction function for creating transactions.
To execute a database transaction with multiple queries, call the transaction function and pass the lambda with these
queries. For example, the function for adding all elements of a list in a single transaction looks like this:
SQLDelight
plugin
for
Android
Studio
To simplify working with .sq generator files, SQLDelight provides a plugin for Android Studio. This plugin adds syntax
highlighting, code completion, usage search, refactoring, displays compile-time errors, and much more.
To install the plugin in Android Studio, open Preferences | Plugins | Marketplace and enter SQLDelight in the search bar.
For more information about the plugin, see the SQLDelight documentation.
We'd like to thank the IceRock team for helping us write this article.
Use
Ktor
for
networking
Conventionally, modern applications with client-server architecture use the HTTP protocol for transferring data between
the server and the client. If your mobile app has a server to exchange data with, an HTTP client is an essential part of this
app that enables its interaction with the server.
For Kotlin projects, we recommend Ktor- a framework for building asynchronous clients and servers. It’s written in
Kotlin and leverages its core features such as coroutines or targeting multiple platforms. For more detailed information,
see the Ktor website.
In Kotlin Multiplatform Mobile (KMM) projects, you can use the Ktor Http Client for interactions with servers. On this page,
we’ll take a brief tour on how to connect the Ktor client to a KMM project, create and configure an HTTP client, and
perform network requests with it.
Connect
Ktor
To use the Ktor HTTP client in your project, connect the client as a Gradle dependency: add the corresponding entries in
the dependencies block of a module’s build file (build.gradle or build.gradle.kts).
Ktor provides separate artifacts for using the HTTP client: a common module and different engines that process the
network request.
432
To use Ktor KMM module in the common code, add the dependency to io.ktor:ktor-client-core to the commonMain
source set in the build.gradle or build.gradle.kts file of the KMM module:
Kotlin
Groovy
commonMain {
dependencies {
implementation "io.ktor:ktor-client-core:$ktor_version"
}
}
Then connect the platform engines by adding the dependencies on them. For Android, add the ktor-client-android
dependency to the corresponding source set:
Kotlin
Groovy
androidMain {
dependencies {
implementation "io.ktor:ktor-client-android:$ktor_version"
}
}
For iOS, add the ktor-client-ios dependency to the corresponding source set:
Kotlin
433
}
Groovy
iosMain {
dependencies {
implementation "io.ktor:ktor-client-ios:$ktor_version"
}
}
For more information about connecting the Ktor client to the multiplatform project, see the Ktor documentation.
Set
up
an
HTTP
client
In Ktor, HTTP clients are represented by the HttpClient class. To create an HTTP client with default settings, call the
HttpClient() constructor:
CIO here is the class that represents an HTTP engine that the client will use. Let’s take a closer look at the available
HTTP engines.
Select
an
engine
Ktor offers you multiple HTTP engines to use in your project: Apache, CIO, Android, iOS, and others. Engines differ by
sets of supported features or platforms they work on. For the full list of supported HTTP engines, refer to the Ktor
documentation.
To use a specific HTTP engine, connect the corresponding Ktor artifact as a dependency, for example:
Kotlin
dependencies {
implementation("io.ktor:ktor-client-cio:$ktor_version")
}
Groovy
dependencies {
implementation "io.ktor:ktor-client-cio:$ktor_version"
}
434
Now you can create an HTTP client with this engine: just pass the engine class as an argument of the HttpClient()
constructor.
If you call the HttpClient() constructor without an argument, then one of the engines available to Ktor will be automatically
selected at compile time.
Mock engine
Ktor offers a special HTTP engine for testing purposes - MockEngine, which simulates HTTP calls without an actual
connection to an API endpoint.
There are several platform-specific implementations of MockEngine. To use them in your KMM project, connect the
corresponding dependencies: io.ktor:ktor-client-mock-jvm for Android io.ktor:ktor-client-mock-native for iOS
Kotlin
dependencies {
testImplementation("io.ktor:ktor-client-mock:$ktor_version")
}
Groovy
dependencies {
api "io.ktor:ktor-client-mock:$ktor_version"
}
For detailed information about testing with Ktor, refer to the Ktor documentation.
Configure
the
client
Client configuration can be done through a lambda expression with the receiver. In other words, the receiver object of the
HttpClientConfig class for a specific HTTP engine through which the entire configuration is performed will be transferred
to the lambda, which is transferred as an argument to the HttpClient() function.
435
val httpClient = HttpClient {
expectSuccess = false
ResponseObserver { response ->
println("HTTP status: ${response.status.value}")
}
}
In this example, the following configuration is used: Receiving HTTP errors in response don’t cause exceptions A
ResponseObserver is created that prints response statuses to the standard output.
Engine configuration
When you create an HTTP client with a specific engine, pass the engine configuration in the same lambda in the engine
block.
Features
Ktor lets you use additional HTTP client functionality (features) that is not available by default, for example, logging,
authorization, or serialization. Most of them are distributed in separate artifacts. To use them, you should connect them
as dependencies to the common source set. For example:
Kotlin
Groovy
commonMain {
dependencies {
implementation "io.ktor:ktor-client-auth:$ktor_version"
}
}
Then, add the required features in the client configuration using the install() function.
436
val client = HttpClient() {
install(Auth) {
// providers config
...
}
}
For example, you can use the ResponseObserver class to set up an observer for responses. At the beginning of the
article, an observer was added using the ResponseObserver{} builder function, which internally calls up the install
function. An observer as additional functionality can be explicitly added as follows:
For the full list of available HTTP client features and instructions on their configuration, see the Ktor documentation.
Create
HTTP
requests
The main function for creating HTTP requests is request- an extension function for the HttpClient class. All the request
settings are generated using the HttpRequestBuilder class. The request function has the suspend modifier, so requests
can be executed in coroutines. For detailed information about creating and sending requests with the Ktor client, see the
Ktor documentation.
Method
To define an HTTP method (for example, GET or POST) for a request, provide a value for the method property: a GET
request whose result comes as a string:
a POST request:
Ktor provides extension functions for the HttpClient class for using basic HTTP methods: get, post, put, patch, delete,
437
options, head. This is how you use them to send a GET request:
Headers
To add headers to the request, use the headers extension function.
headers {
append("Accept", "application/json")
append("Authorization", "oauth token")
}
}
Body
To set the body of a request, assign a value to the body property in the HttpRequestBuilder class. You can assign a string
or an OutgoingContent object to this property. For example, sending data with a text/plain text MIME type can be
implemented as follows:
body = TextContent(
text = "Body content",
contentType = ContentType.Text.Plain
)
}
Response
type
To obtain more information in the response, such as HTTP status, you can use the HttpResponse type as the request
result:
438
For more information about the HttpResponse, refer to the Documentation.
You can also obtain the request results in the form of a byte array:
Multipart
requests
To send a multipart request, pass a MultiPartFormDataContent object to the body property. Create this object by calling
the MultiPartFormDataContent() constructor with the argument parts: List<PartData>. To create this list, use the
FormBuilder builder class. It provides multiple variations of the append function for adding the data. There is also
formData builder function, which accepts a lambda with the FormBuilder receiver.
An example of creating a POST request with Multipart data may look as follows:
Concurrency
The Ktor API is based on suspend functions, so Kotlin coroutines are used when working with asynchronous requests.
Therefore, all requests must be executed in coroutines, which will suspend their execution while awaiting a response.
For concurrent execution of two or more requests, you can use coroutine builders: launch or async. For example, sending
two concurrent requests using async might look as follows:
httpClient.close()
}
439
Close
the
HTTP
client
After you finish working with the HTTP client, don’t forget to free up the resources that it uses: threads, connections,
and CoroutineScope for coroutines. To do this, call up the close() function in HttpClient:
httpClient.close()
If you need to use HttpClient for a single request, call the extension function use() that will automatically calls close() after
executing the code block:
Note that the close function prohibits the creation of new requests, but doesn’t terminate currently active ones.
Resources will only be released after all client requests are completed
We'd like to thank the IceRock team for helping us write this article.
Publish
KMM
apps
Once your mobile apps are ready for release, it’s time to deliver them to the users by publishing them in app stores.
Multiple stores are available for each platform. However, in this article we’ll focus on the official ones: Google Play
Store and Apple App Store. You’ll learn how to prepare Kotlin Multiplatform Mobile (KMM) applications for publishing,
and we’ll highlight the parts of this process that deserve special attention.
Android
app
Since Kotlin is the main language for Android development, KMM has no obvious effect on compiling the project and
building the Android app. Both the Android library produced from the shared module and the Android app itself are typical
Android Gradle modules; they are no different from other Android libraries and apps. Thus, publishing the Android app
from a KMM project is no different from the usual process described in the Android developer documentation.
iOS
app
The iOS app from a KMM project is built from a typical Xcode project, so the main stages involved in publishing it are the
same as described in the iOS developer documentation.
What is specific to KMM projects is compiling the shared Kotlin module into a framework and linking it to the Xcode
project. Generally, all integration between the shared module and the Xcode project is done automatically by the Kotlin
Multiplatform Mobile plugin for Android Studio. However, if you don’t use the plugin, bear in mind the following when
building and bundling the iOS project in Xcode:
440
The shared Kotlin library compiles down to the native framework.
You need to connect the framework compiled for the specific platform to the iOS app project.
In the Xcode project settings, specify the path to the framework to search for the build system.
After building the project, you should launch and test the app to make sure that there are no issues when working with
the framework in runtime.
There are two ways you can connect the shared Kotlin module to the iOS project:
Use the Kotlin/Native Cocoapods plugin, which allows you to use a multiplatform project with native targets as a
CocoaPods dependency in your iOS project.
Manually configure your Multiplatform project to create an iOS framework and the XCode project to obtain its latest
version. KMM Android Studio Plugin usually does this configuration. Understand the project structure to implement it
yourself.
Symbolicating
crash
reports
To help developers make their apps better, iOS provides a means for analyzing app crashes. For detailed crash analysis,
it uses special debug symbol (.dSYM) files that match memory addresses in crash reports with locations in the source
code, such as functions or line numbers.
By default, the release versions of iOS frameworks produced from the shared Kotlin module have an accompanying
.dSYM file. This helps you analyze crashes that happen in the shared module’s code.
When an iOS app is rebuilt from bitcode, its dSYM file becomes invalid. For such cases, you can compile the shared
module to a static framework that stores the debug information inside itself. For instructions on setting up crash report
symbolication in binaries produced from Kotlin modules, see the Kotlin/Native documentation.
Concurrency
overview
When you extend your development experience from Android to Kotlin Multiplatform Mobile, you will encounter a different
state and concurrency model for iOS. This is a Kotlin/Native model. Kotlin/Native is a technology for compiling Kotlin
code to native binaries that can run without a virtual machine, for example on iOS.
Having mutable memory available to multiple threads at the same time, if unrestricted, is known to be risky and prone to
error. Languages like Java, C++, and Swift/Objective-C let multiple threads access the same state in an unrestricted way.
Concurrency issues are unlike other programming issues in that they are often very difficult to reproduce. You may not
see them locally while developing, and they may happen sporadically. And sometimes you can only see them in
production under load.
In short, just because your tests pass, you can’t necessarily be sure that your code is OK.
Not all languages are designed this way. JavaScript simply does not allow you to access the same state concurrently. At
the other end of the spectrum is Rust, with its language-level management of concurrency and states, which makes it
441
very popular.
Rules
for
state
sharing
Kotlin/Native introduces rules for sharing states between threads. These rules exist to prevent unsafe shared access to
mutable states. If you come from a JVM background and write concurrent code, you may need to change the way you
architect your data, but doing so will allow you to achieve the same results without risky side effects.
It is also important to point out that there are ways to work around these rules. The intent is to make working around
these rules something that you rarely have to do, if ever.
There are just two simple rules regarding state and concurrency.
Rule
1:
Mutable
state
==
1
thread
If your state is mutable, only one thread can see it at a time. Any regular class state that you would normally use in Kotlin
is considered by the Kotlin/Native runtime as mutable. If you aren't using concurrency, Kotlin/Native behaves the same as
any other Kotlin code, with the exception of global state.
fun simpleState(){
val sd = SomeData(42)
sd.count++
println("My count is ${sd.count}") // It will be 43
}
If there's only one thread, you won’t have concurrency issues. Technically this is referred to as thread confinement,
which means that you cannot change the UI from a background thread. Kotlin/Native's state rules formalize that concept
for all threads.
Rule
2:
Immutable
state
==
many
threads
If a state can't be changed, multiple threads can safely access it. In Kotlin/Native, immutable doesn't mean everything is a
val. It means frozen state.
Immutable
and
frozen
state
The example below is immutable by definition – it has 2 val elements, and both are of final immutable types.
This next example may be immutable or mutable. It is not clear what SomeInterface will do internally at compile time. In
Kotlin, it is not possible to determine deep immutability statically at compile time.
442
data class SomeData(val s:String, val i:SomeInterface)
Kotlin/Native needs to verify that some part of a state really is immutable at runtime. The runtime could simply go through
the whole state and verify that each part is deeply immutable, but that would be inflexible. And if you needed to do that
every time the runtime wanted to check mutability, there would be significant consequences for performance.
Kotlin/Native defines a new runtime state called frozen. Any instance of an object may be frozen. If an object is frozen:
1. You cannot change any part of its state. Attempting to do so will result in a runtime exception:
InvalidMutabilityException. A frozen object instance is 100%, runtime-verified, immutable.
2. Everything it references is also frozen. All other objects it has a reference to are guaranteed to be frozen. This means
that, when the runtime needs to determine whether an object can be shared with another thread, it only needs to
check whether that object is frozen. If it is, the whole graph is also frozen and is safe to be shared.
The Native runtime adds an extension function freeze() to all classes. Calling freeze() will freeze an object, and everything
referenced by the object, recursively.
Freezing
state
freeze() is not available in shared Kotlin code, but several libraries provide expect and actual declarations for using it in
shared code. However, if you're using a concurrency library, like kotlinx.coroutines, it will likely freeze data that
crosses thread boundaries automatically.
443
freeze is not unique to Kotlin. You can also find it in Ruby and JavaScript.
Global
state
Kotlin allows you to define a state as globally available. If left simply mutable, the global state would violate Rule 1.
To conform to Kotlin/Native's state rules, the global state has some special conditions. These conditions freeze the state
or make it visible only to a single thread.
Global
object
Global object instances are frozen by default. This means that all threads can access them, but they are immutable. The
following won't work.
object SomeState{
var count = 0
fun add(){
count++ //This will throw an exception
}
}
Trying to change count will throw an exception because SomeState is frozen (which means all of its data is frozen).
You can make a global object thread local, which will allow it to be mutable and give each thread a copy of its state.
Annotate it with @ThreadLocal.
@ThreadLocal
object SomeState{
var count = 0
fun add(){
count++ //ðŸ‘
}
}
If different threads read count, they'll get different values, because each thread has its own copy.
class SomeState{
companion object{
var count = 0
fun add(){
count++ //This will throw an exception
}
}
}
Global
properties
444
Global properties are a special case. They are only available to the main thread, but they are mutable. Accessing them
from other threads will throw an exception.
@ThreadLocal, which will give each thread its own mutable copy.
This rule applies to global properties with backing fields. Computed properties and global functions do not have the main
thread restriction.
Current
and
future
models
Kotlin/Native's concurrency rules will require some adjustment in architecture design, but with the help of libraries and
new best practices, day to day development is basically unaffected. In fact, adhering to Kotlin/Native's rules regarding
multiplatform code will result in safer concurrency across the KMM application. You can try out the Kotlin/Native
concurrency model in this hands-on tutorial.
In the KMM application, you have Android and iOS targets with different state rules. Some teams, generally ones working
on larger applications, share code for very specific functionality, and often manage concurrency in the host platform. This
will require explicit freezing of states returned from Kotlin, but otherwise, it is straightforward.
A more extensive model, where concurrency is managed in Kotlin and the host communicates on its main thread to
shared code, is simpler from a state management perspective. Concurrency libraries, like kotlinx.coroutines, will help
automate freezing. You'll also be able to leverage the power of coroutines in your code and increase efficiency by sharing
more code.
However, the current Kotlin/Native concurrency model has a number of deficiencies. For example, mobile developers are
used to freely sharing their objects between threads, and they have already developed a number of approaches and
architectural patterns to avoid data races while doing so. It is possible to write efficient applications that do not block the
main thread using Kotlin/Native, but the ability to do so comes with a steep learning curve.
That's why we are working on creating a new memory manager and concurrency model for Kotlin/Native that will help us
remove these drawbacks. Learn more about where we are going with this.
Concurrent
mutability
When it comes to working with iOS, Kotlin/Native's state and concurrency model has two simple rules.
445
2. An immutable, frozen state can be shared between threads.
The result of following these rules is that you can't change global states, and you can't change the same shared state
from multiple threads. In many cases, simply changing your approach to how you design your code will work fine, and
you don't need concurrent mutability. States were mutable from multiple threads in JVM code, but they didn't need to be.
However, in many other cases, you may need arbitrary thread access to a state, or you may have service objects that
should be available to the entire application. Or maybe you simply don't want to go through the potentially costly exercise
of redesigning existing code. Whatever the reason, it will not always be feasible to constrain a mutable state to a single
thread.
There are various techniques that help you work around these restrictions, each with their own pros and cons:
Atomics
Thread-isolated states
Low-level capabilities
Atomics
Kotlin/Native provides a set of Atomic classes that can be frozen while still supporting changes to the value they contain.
These classes implement a special-case handling of states in the Kotlin/Native runtime. This means that you can change
values inside a frozen state.
The Kotlin/Native runtime includes a few different variations of Atomics. You can use them directly or from a library.
Kotlin provides an experimental low-level kotlinx.atomicfu library that is currently used only for internal purposes and is
not supported for general usage. You can also use Stately, a utility library for multiplatform compatibility with
Kotlin/Native-specific concurrency, developed by Touchlab.
AtomicInt/AtomicLong
The first two are simple numerics: AtomicInt and AtomicLong. They allow you to have a shared Int or Long that can be
read and changed from multiple threads.
object AtomicDataCounter {
val count = AtomicInt(3)
fun addOne() {
count.increment()
}
}
The example above is a global object, which is frozen by default in Kotlin/Native. In this case, however, you can change
the value of count. It's important to note that you can change the value of count from any thread.
446
AtomicReference
AtomicReference holds an object instance, and you can change that object instance. The object you put in
AtomicReference must be frozen, but you can change the value that AtomicReference holds. For example, the following
won't work in Kotlin/Native:
object GlobalData {
var sd = SomeData(0)
According to the rules of global state, global object values are frozen in Kotlin/Native, so trying to modify sd will fail. You
could implement it instead with AtomicReference:
object GlobalData {
val sd = AtomicReference(SomeData(0).freeze())
The AtomicReference itself is frozen, which lets it live inside something that is frozen. The data in the AtomicReference
instance is explicitly frozen in the code above. However, in the multiplatform libraries, the data will be frozen
automatically. If you use the Kotlin/Native runtime's AtomicReference, you should remember to call freeze() explicitly.
AtomicReference can be very useful when you need to share a state. There are some drawbacks to consider, however.
Accessing and changing values in an AtomicReference is very costly performance-wise relative to a standard mutable
state. If performance is a concern, you may want to consider using another approach involving a thread-isolated state.
There is also a potential issue with memory leaks, which will be resolved in the future. In situations where the object kept
in the AtomicReference has cyclical references, it may leak memory if you don't explicitly clear it out:
If you have state that may have cyclic references and needs to be reclaimed, you should use a nullable type in the
AtomicReference and set it to null explicitly when you're done with it.
If you're keeping AtomicReference in a global object that never leaves scope, this won't matter (because the memory
never needs to be reclaimed during the life of the process).
class Container(a:A) {
val atom = AtomicReference<A?>(a.freeze())
/**
* Call when you're done with Container
*/
447
fun clear(){
atom.value = null
}
}
Finally, there's also a consistency concern. Setting/getting values in AtomicReference is itself atomic, but if your logic
requires a longer chain of thread exclusion, you'll need to implement that yourself. For example, if you have a list of values
in an AtomicReference and you want to scan them first before adding a new one, you'll need to have some form of
concurrency management that AtomicReference alone does not provide.
The following won't protect against duplicate values in the list if called from multiple threads:
object MyListCache {
val atomicList = AtomicReference(listOf<String>().freeze())
fun addEntry(s:String){
val l = atomicList.value
val newList = mutableListOf<String>()
newList.addAll(l)
if(!newList.contains(s)){
newList.add(s)
}
atomicList.value = newList.freeze()
}
}
You will need to implement some form of locking or check-and-set logic to ensure proper concurrency.
Thread-isolated
state
Rule 1 of Kotlin/Native state is that a mutable state is visible to only one thread. Atomics allow mutability from any thread.
Isolating a mutable state to a single thread, and allowing other threads to communicate with that state, is an alternative
method for achieving concurrent mutability.
To do this, create a work queue that has exclusive access to a thread, and create a mutable state that lives in just that
thread. Other threads communicate with the mutable thread by scheduling work on the work queue.
Data that goes in or comes out, if any, needs to be frozen, but the mutable state hidden in the worker thread remains
mutable.
Conceptually it looks like the following: one thread pushes a frozen state into the state worker, which stores it in the
mutable state container. Another thread later schedules work that takes that state out.
448
Thread-
isolated
state
Implementing thread-isolated states is somewhat complex, but there are libraries that provide this functionality.
AtomicReference
vs.
thread-isolated
state
For simple values, AtomicReference will likely be an easier option. For cases with significant states, and potentially
significant state changes, using a thread-isolated state may be a better choice. The main performance penalty is actually
crossing over threads. But in performance tests with collections, for example, a thread-isolated state significantly
outperforms a mutable state implemented with AtomicReference.
The thread-isolated state also avoids the consistency issues that AtomicReference has. Because all operations happen in
the state thread, and because you're scheduling work, you can perform operations with multiple steps and guarantee
consistency without managing thread exclusion. Thread isolation is a design feature of the Kotlin/Native state rules, and
isolating mutable states works with those rules.
The thread-isolated state is also more flexible insofar as you can make mutable states concurrent. You can use any type
of mutable state, rather than needing to create complex concurrent implementations.
Low-level
capabilities
Kotlin/Native has some more advanced ways of sharing concurrent states. To achieve high performance, you may need
to avoid the concurrency rules altogether.
This is a more advanced topic. You should have a deep understanding of how concurrency in Kotlin/Native
works under the hood, and you’ll need to be very careful when using this approach. Learn more about
concurrency.
449
Kotlin/Native runs on top of C++ and provides interop with C and Objective-C. If you are running on iOS, you can also
pass lambda arguments into your shared code from Swift. All of this native code runs outside of the Kotlin/Native state
restrictions.
That means that you can implement a concurrent mutable state in a native language and have Kotlin/Native talk to it.
You can use Objective-C interop to access low-level code. You can also use Swift to implement Kotlin interfaces or pass
in lambdas that Kotlin code can call from any thread.
One of the benefits of a platform-native approach is performance. On the negative side, you'll need to manage
concurrency on your own. Objective-C does not know about frozen, but if you store states from Kotlin in Objective-C
structures, and share them between threads, the Kotlin states definitely need to be frozen. Kotlin/Native's runtime will
generally warn you about issues, but it's possible to cause concurrency problems in native code that are very, very
difficult to track down. It is also very easy to create memory leaks.
Since in the KMM application you are also targeting the JVM, you'll need alternate ways to implement anything you use
platform native code for. This will obviously take more work and may lead to platform inconsistencies.
Concurrency
and
coroutines
When working with mobile platforms, you may need to write multithreaded code that runs in parallel. For this, you can use
the standard kotlinx.coroutines library or its multithreaded version and alternative solutions.
Review the pros and cons of each solution and choose the one that works best for your situation.
Learn more about concurrency, the current approach, and future improvements.
Coroutines
Coroutines are light-weight threads that allow you to write asynchronous non-blocking code. Kotlin provides the
kotlinx.coroutines library with a number of high-level coroutine-enabled primitives.
The current version of kotlinx.coroutines, which can be used for iOS, supports usage only in a single thread. You cannot
send work to other threads by changing a dispatcher.
You can suspend execution and do work on other threads while using a different mechanism for scheduling and
managing that work. However, this version of kotlinx.coroutines cannot change threads on its own.
There is also another version of kotlinx.coroutines that provides support for multiple threads.
450
Dispatcher for changing threads
Asynchronous
vs.
parallel
processing
Asynchronous and parallel processing are different.
Within a coroutine, the processing sequence may be suspended and resumed later. This allows for asynchronous, non-
blocking code, without using callbacks or promises. That is asynchronous processing, but everything related to that
coroutine can happen in a single thread.
The following code makes a network call using Ktor. In the main thread, the call is initiated and suspended, while another
underlying process performs the actual networking. When completed, the code resumes in the main thread.
That is different from parallel code that needs to be run in another thread. Depending on your purpose and the libraries
you use, you may never need to use multiple threads.
Dispatcher
for
changing
threads
Coroutines are executed by a dispatcher that defines which thread the coroutine will be executed on. There are a number
of ways in which you can specify the dispatcher, or change the one for the coroutine. For example:
withContext takes both a dispatcher as an argument and a code block that will be executed by the thread defined by the
dispatcher. Learn more about coroutine context and dispatchers.
To perform work on a different thread, specify a different dispatcher and a code block to execute. In general, switching
dispatchers and threads works similar to the JVM, but there are differences related to freezing captured and returned
data.
Frozen
captured
data
To run code on a different thread, you pass a functionBlock, which gets frozen and then runs in another thread.
451
You will call that function as follows:
runOnDifferentThread {
//Code run in another thread
}
As described in the concurrency overview, a state shared between threads in Kotlin/Native must be frozen. A function
argument is a state itself, which will be frozen along with anything it captures.
Coroutine functions that cross threads use the same pattern. To allow function blocks to be executed on another thread,
they are frozen.
In the following example, the data class instance dc will be captured by the function block and will be frozen when
crossing threads. The println statement will print true.
val dc = DataClass("Hello")
withContext(Dispatchers.Default) {
println("${dc.isFrozen}")
}
When running parallel code, be careful with the captured state. Sometimes it's obvious when the state will be captured,
but not always. For example:
The code inside saveData runs on another thread. That will freeze id, but because id is a property of the parent class, it
will also freeze the parent class.
Frozen
returned
data
Data returned from a different thread is also frozen. Even though it's recommended that you return immutable data, you
can return a mutable state in a way that doesn't allow a returned value to be changed.
val dc = withContext(Dispatchers.Default) {
DataClass("Hello Again")
}
println("${dc.isFrozen}")
It may be a problem if a mutable state is isolated in a single thread and coroutine threading operations are used for
communication. If you attempt to return data that retains a reference to the mutable state, it will also freeze the data by
association.
452
Multithreaded
coroutines
A special branch of the kotlinx.coroutines library provides support for using multiple threads. It is a separate branch for
the reasons listed in the future concurrency model blog post.
However, you can still use the multithreaded version of kotlinx.coroutines in production, taking its specifics into account.
To use the multithreaded version, add a dependency for the commonMain source set in build.gradle.kts:
commonMain {
dependencies {
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.5.2-native-mt"
}
}
When using other libraries that also depend on kotlinx.coroutines, such as Ktor, make sure to specify the multithreaded
version of kotlinx-coroutines. You can do this with strictly:
implementation ("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.5.2-native-mt"){
version {
strictly("1.5.2-native-mt")
}
}
Because the main version of kotlinx.coroutines is a single-threaded one, libraries will almost certainly rely on this version.
If you see InvalidMutabilityException related to a coroutine operation, it's very likely that you are using the wrong version.
Using multithreaded coroutines may result in memory leaks. This can be a problem for complex coroutine
scenarios under load. We are working on a solution for this.
Alternatives
to
kotlinx-coroutines
There are a few alternative ways to run parallel code.
CoroutineWorker
CoroutinesWorker is a library published by AutoDesk that implements some features of coroutines across threads using
the single-threaded version of kotlinx.coroutines.
For simple suspend functions this is a pretty good option, but it does not support Flow and other structures.
453
Reaktive
Reaktive is an Rx-like library that implements Reactive extensions for Kotlin Multiplatform. It has some coroutine
extensions but is primarily designed around RX and threads.
Custom
processor
For simpler background tasks, you can create your own processor with wrappers around platform specifics. See a simple
example.
Platform
concurrency
In production, you can also rely on the platform to handle concurrency. This could be helpful if the shared Kotlin code will
be used for business logic or data operations rather than architecture.
To share a state in iOS across threads, that state needs to be frozen. The concurrency libraries mentioned here will freeze
your data automatically. You will rarely need to do so explicitly, if ever.
If you return data to the iOS platform that should be shared across threads, ensure that data is frozen before leaving the
iOS boundary.
Kotlin has the concept of frozen only for Kotlin/Native platforms including iOS. To make freeze available in common code,
you can create expect and actual implementations for freeze, or use stately-common, which provides this functionality. In
Kotlin/Native, freeze will freeze your state, while on the JVM it'll do nothing.
To use stately-common, add a dependency for the commonMain source set in build.gradle.kts:
commonMain {
dependencies {
implementation "co.touchlab:stately-common:1.0.x"
}
}
Samples
This is a curated list of Kotlin Multiplatform Mobile (KMM) samples.
Do you have a great idea for a sample, or one you would like to add to the list?
Feel free to reach out to us and tell us about it!
454
Sample name What's Popular libraries UI iOS Platform Tests JS Features
shared? used Framework integration APIs target
kmm- Models, SQLDelight, Ktor, Jetpack Xcode build ✅ - - Redux for
production- Networking, DateTime, Compose, phases
sharing UI
sample Data multiplatform- SwiftUI
Storage, UI settings, Napier, State
State kotlinx.serialization
Published to
Google Play
and App Store
Network layer
generation
from OpenAPI.
455
Sample name What's Popular libraries UI iOS Platform Tests JS Features
shared? used Framework integration APIs target
PeopleInSpace Models, Koin, SQLDelight, Jetpack CocoaPods, - ✅ ✅ Android Wear
Networking, Ktor Compose, Swift
OS
Data Storage SwiftUI Packages
iOS
watchOS
macOS
Desktop
(Compose for
Desktop)
Web
(Compose for
Web)
Web (Kotlin/JS
+ React
Wrapper)
JVM
GitFox SDK Models, Ktor XML, UIKit Xcode build - - ✅ Integrated into
Networking, phases
Flutter app
Interactors
D-KMP- Networking, SQLDelight, Ktor, Jetpack Xcode build - ✅ ✅ Implements the
sample Data DateTime, Compose, phases
MVI pattern
Storage, multiplatform- SwiftUI
ViewModels, settings and the
Navigation unidirectional
data flow
Uses Kotlin's
StateFlow to
trigger UI layer
recompositions
456
Sample name What's Popular libraries UI iOS Platform Tests JS Features
shared? used Framework integration APIs target
Currency Models, Ktor, SQLDelight, XML, CocoaPods ✅ ✅ - Logic shared
Converter Networking, koin, moko- SwiftUI with the
Calculator Data resources,
Storage, kotlinx.datetime, backend
Algorithms, multiplatform-
ViewModels settings
todoapp Models, SQLDelight, Jetpack Xcode build - ✅ ✅ 99% of the
Networking, Decompose, Compose, phases
code is shared
Presentation, MVIKotlin, Reaktive SwiftUI
Navigation
MVI
and UI
architectural
pattern
Shared UI
across
Android,
Desktop and
Web via
Compose
Multiplatform
457
Sample name What's Popular libraries UI iOS Platform Tests JS Features
shared? used Framework integration APIs target
Codeforces Models, SQLDelight, Ktor, XML, UIKit CocoaPods ✅ ✅ - Uses Redux
WatchR Networking, kotlinx.serialization
(ReKamp) for
Data
Storage, UI sharing UI
State State
Published to
Google Play
and App Store
kmm-with- - - - CocoaPods - - - -
cocoapods-
multitarget-
xcode-sample
FAQ
What
is
KMM?
KMM (Kotlin Multiplatform Mobile) is an SDK for cross-platform mobile development. With KMM, you can develop
multiplatform mobile applications and share parts of your applications between Android and iOS, such as core layers,
business logic, presentation logic, and more.
KMM uses the multiplatform abilities of Kotlin and the features designed for mobile development, such as CocoaPods
integration and the Android Studio Plugin.
You may want to watch this introductory video, in which Kotlin Developer Advocate Ekaterina Petrova explains in detail
what Kotlin Multiplatform Mobile is and how you can use it in your projects. Together with Ekaterina you'll set up an
environment and prepare for creating your first cross-platform mobile application with KMM.
What
is
the
KMM
plugin?
458
The Kotlin Multiplatform Mobile (KMM) plugin for Android Studio helps you develop applications that work on both
Android and iOS.
Run, test, and debug the iOS part of your application on iOS targets straight from Android Studio.
The KMM plugin works only on macOS. This is because iOS simulators, per the Apple requirement, can run only on
macOS but not on any other operating systems, such as Microsoft Windows or Linux.
The good news is that you can work with KMM projects on Android even without the KMM plugin. If you are going to work
with shared code or Android-specific code, you can work on any operating system supported by Android Studio.
What
is
Kotlin/Native
and
how
does
it
relate
to
KMM?
Kotlin/Native is a technology for compiling Kotlin code to native binaries, which can run without a virtual machine. It
consists of an LLVM -based backend for the Kotlin compiler and a native implementation of the Kotlin standard library.
Kotlin/Native is primarily designed to allow compilation for platforms where virtual machines are not desirable or possible,
such as embedded devices and iOS. It is particularly suitable for situations when the developer needs to produce a self-
contained program that does not require an additional runtime or virtual machine. And that is exactly the case with iOS
development.
Shared code, written in Kotlin, is compiled to JVM bytecode for Android with Kotlin/JVM and to native binaries for iOS
with Kotlin/Native. It makes the integration with KMM seamless on both platforms.
459
Kotlin/Native and Kotlin/JVM binaries
What
are
the
plans
for
KMM?
KMM is one of the focus areas of the Kotlin roadmap. To see which parts we’re working on right now, check out the
roadmap details. Most of the recent KMM changes affect the Kotlin Multiplatform and Kotlin/Native sections.
Can
I
run
an
iOS
application
on
Microsoft
Windows
or
Linux?
If you want to write iOS-specific code and run an iOS application on a simulated or real device, use a Mac with a macOS
(use the KMM plugin for it). This is because iOS simulators can run only on macOS, per the Apple requirement, but cannot
run on other operating systems, such as Microsoft Windows or Linux.
If you are going to work with shared code or Android-specific code, you can work on any operating system supported by
Android Studio.
Where
can
I
get
complete
examples
to
play
with?
460
Curated samples
In
which
IDE
should
I
work
on
my
cross-platform
app?
You can work in Android Studio. Android Studio allows the use of the KMM plugin, which is a part of the KMM ecosystem.
Enable the KMM plugin in Android Studio if you want to write iOS-specific code and launch an iOS application on a
simulated or real device. The KMM plugin can be used only on macOS.
Most of our adopters use Android Studio. However, if there is any reason for you not to use it, there is another option: you
can use IntelliJ IDEA. IntelliJ IDEA provides the ability to create a multiplatform mobile application from the Project Wizard,
but you won’t be able to launch an iOS application from the IDE.
How
can
I
write
concurrent
code
in
KMM
projects?
You can learn how to work with concurrency on the documentation portal.
Working with concurrent code in KMM projects might not seem straightforward, as different memory management
approaches are used in Kotlin/JVM and Kotlin/Native. The current approach for Kotlin/Native has some limitations. The
new Kotlin/Native memory management model is on the roadmap and the team is working on a solution for it.
How
can
I
speed
up
my
KMM
module
compilation
for
iOS?
See these tips for improving Kotlin/Native compilation times.
Introduce
your
team
to
KMM
These recommendations will help you introduce your team to KMM:
461
Start
with
empathy
Software development is a team game, with each critical decision needing the approval of all team members. Integrating
any cross-platform technology will significantly affect the development process for your mobile application. So before you
start integrating Kotlin Multiplatform Mobile in your project, you’ll need to introduce your team to the technology and
guide them gently to see it's worth adopting.
Understanding the people who work on your project is the first step to successful integration. Your boss is responsible for
delivering features with the best quality in the shortest time possible. To them, any new technology is a risk. Your
colleagues have a different perspective, as well. They have experience building apps with the “native†technology
stack. They know how to write the UI and business logic, work with dependencies, test, and debug code in the IDE, and
they are already familiar with the language. Switching to a different ecosystem is very uncomfortable, as it always means
leaving your comfort zone.
Given all that, be ready to face lots of biases and answer a lot of questions when advocating for the move to KMM. As
you do, never lose sight of what your team needs. Some of the advice below might be useful for preparing your KMM
pitch.
Explain
how
it
works
At this stage, you need to get rid of any preexisting bad feelings about cross-platform applications and show that using
KMM in your project is not only possible but also won't bring regular cross-platform problems. You should explain why
there won't be any problems, such as:
Limitations of using all iOS and Android features – Whenever a task cannot be solved in the shared code or
whenever you want to use specific native features, you can use the expect/actual pattern to seamlessly write platform-
specific code.
Performance issues – Shared code written in Kotlin is compiled to different output formats for different targets: to
Java bytecode for Android and to native binaries for iOS. Thus, there is no additional runtime overhead when it comes
to executing this code on platforms, and the performance is comparable to native apps.
Legacy code problems – No matter how large your project is, your existing code will not prevent you from integrating
KMM. You can start writing cross-platform code at any moment and connect it to your iOS and Android Apps as a
regular dependency, or you can use the code you’ve already written and simply modify it to be compatible with
iOS.
Being able to explain how KMM works is important, as nobody likes when a discussion of technology seems to rely on
magic. People might think the worst if anything is unclear to them, so be careful not to make the mistake of thinking
something is too obvious to warrant explanation. Instead try to explain all the basic concepts before moving on to the
next stage. This document on multiplatform programming could help you systemize your knowledge to prepare for this
experience.
Show
the
value
462
Understanding how the technology works is necessary, but not enough. Your team needs to see the gains of using it, and
the way you present these gains should be related to your product. Kotlin Multiplatform Mobile allows you to use a single
codebase for the business logic of iOS and Android apps. So if you develop a very thin client and the majority of the code
is UI logic, then the main power of Kotlin Multiplatform Mobile will be unused in your project. However, if your application
has complex business logic, for example if you have features like networking, data storage, payments, complex
computations, or data synchronization, then this logic could easily be written and shared between iOS and Android so you
can experience the real power of KMM.
At this stage, you need to explain the main gains of using KMM in your product. One of the ways to do this is to share
stories of other companies who already benefit from KMM. The successful experience of these teams, especially ones
with similar product objectives, could become a key factor in the final decision.
Citing case studies of different companies who already use KMM in production could significantly help you make a
compelling argument:
Chalk.com – The UI for each of the Chalk.com apps is native to the platform, but otherwise almost everything for
their apps can be shared with Kotlin Multiplatform Mobile.
Cash App – A lot of the app’s business logic, including the ability to search through all transactions, is
implemented with Kotlin Multiplatform Mobile.
Yandex.Disk – They started out by experimenting with the integration of a small feature, and as the experiment was
considered successful, they implemented their whole data synchronization logic in KMM.
Offer
proof
The theory is good, but putting it into practice is ultimately most important. As one option to make your case more
convincing, you can take the risky choice of devoting some of your personal free time to creating something with KMM
and then bringing in the results for your team to discuss. Your prototype could be some sort of test project, which you
would write from scratch and which would demonstrate features that are needed in your application. Networking & data
storage – hands-on tutorial can guide you well on this process.
The more relevant examples could be produced by experimenting with your current project. You could take one existing
feature implemented in Kotlin and make it cross-platform, or you could even create a new Multiplatform Module in your
existing project, take one non-priority feature from the bottom of the backlog, and implement it in the shared module.
Make your Android application work on iOS – tutorial provides a step-by-step guide based on a sample project.
The new Kotlin Multiplatform Mobile plugin for Android Studio will allow you to accomplish either of these tasks in the
shortest amount of time by using the New KMM Application or New KMM Module wizards.
Prepare
for
questions
No matter how detailed your pitch is, your team will have a lot of questions. Listen carefully, and try to answer them all
patiently. You might expect the majority of the questions to come from the iOS part of the team, as they are the
463
developers who aren’t used to seeing Kotlin in their everyday developer routine. This list of some of the most
common questions could help you here:
Q: I heard applications based on cross-platform technologies can be rejected from the AppStore. Is taking this risk worth
it?
A: The Apple Store has strict guidelines for application publishing. One of the limitations is that apps may not download,
install, or execute code which introduces or changes features or functionality of the app (App Store Review Guideline
2.5.2). This is relevant for some cross-platform technologies, but not for KMM. Shared Kotlin code compiles to native
binaries with Kotlin/Native, bundles a regular iOS framework into your app, and doesn't provide the ability for dynamic
code execution.
Q: Multiplatform projects are built with Gradle, and Gradle has an extremely steep learning curve. Do I need to spend a lot
of time now trying to configure my project?
A: There’s actually no need. There are various ways to organize the work process around building KMM applications.
First, only Android developers could be responsible for the builds, in which case the iOS team would only write code or
even only consume the resulting artifact. You also can organize some workshops or practice pair programming while
facing tasks that require working with Gradle, and this would increase your team’s Gradle skills. You can explore
different ways of and choose the one that’s most appropriate for your team.
Also, in basic scenarios, you simply need to configure your project at the start, and then you just add dependencies to it.
The new AS plugin makes configuring your project much easier, so it can now be done in a few clicks.
When only the Android part of the team works with shared code, the iOS developers don’t even need to learn Kotlin.
But when you are ready for your team to move to the next stage, where everyone contributes to the shared code, making
the transition won’t take much time. The similarities between the syntax and functionality of Swift and Kotlin greatly
reduce the work required to learn how to read and write shared Kotlin code. Try it yourself!
Q: I heard that KMM is experimental technology. Does that mean that we shouldn't use it for production?
A: Experimental status means we and the whole Kotlin community are just trying out an idea, but if it doesn't work, it may
be dropped anytime. However, after the release of Kotlin 1.4, KMM is in Alpha status. This means the Kotlin team is fully
committed to working to improve and evolve this technology and will not suddenly drop it. However, before going Beta,
there could be some migration issues yet. But even experimental status doesn’t prevent a feature from being used
successfully in production, as long as you understand all the risks. Check the Kotlin evolution page for information about
the stability statuses of KMM components.
Q: There are not enough multiplatform libraries to implement the business logic, it's much easier to find native
alternatives.
A: Of course, we can't compare the number of multiplatform libraries with React Native, for example. But it took five years
for React Native to expand their ecosystem to its current size. Kotlin Multiplatform Mobile is still young, but the ecosystem
has tremendous potential as there are already a lot of modern libraries written in Kotlin that can be easily ported to
multiplatform.
It’s also a great time to be an iOS developer in the KMM open-source community because the iOS experience is in
demand and there are plenty of opportunities to gain recognition from iOS-specific contributions.
And the more your team digs into KMM, the more interesting and complex their questions will be. Don't worry if you don't
464
have the answers – Kotlin Multiplatform has a large and supportive community in the Kotlin Slack, where a lot of
developers who already use KMM can help you. We would be very thankful if you could share with us the most popular
questions asked by your team. This information will help us understand what topics need to be covered in the KMM
documentation.
Be
supportive
After you decide to use KMM, there will be an adaptation period as your team experiments with the technology. And your
mission will not be over yet! By providing continuous support for your teammates, you will reduce the time it takes for
your team to dive into the technology and achieve their first results.
Here are some tips on how you can support your team at this stage:
Collect the questions you were asked during the previous stage on the “ KMM: Frequently asked questions†wiki
page and share it with your team.
Create a #kmm-support slack channel and become the most active user there.
Organize an informal team building event with popcorn and pizza where you watch educational or inspirational videos
about KMM. “Shipping a Mobile Multiplatform Project on iOS & Android †by Ben Asher & Alec Strong could be a
good choice.
The reality is that you probably will not change people's hearts and minds in a day or even a week. But patience and
attentiveness to the needs of your colleagues will undoubtedly bring results.
The Kotlin Multiplatform Mobile team looks forward to hearing your story of using KMM.
We'd like to thank the Touchlab team for helping us write this article.
Create
a
multiplatform
library
This section provides steps for creating a multiplatform library. You can also complete the tutorial where you will create a
multiplatform library, test it, and publish it to Maven.
3. Enter a project name, then in the Multiplatform section select Library as the project template.
465
Select a project template
5. Click Next.
You can finish creating the project by clicking Finish on the next screen or configure it if necessary:
7. Configure target settings, such as the target template, JVM target version, and test framework.
466
Configure the project
JVM modules
467
Add module dependencies
9. Click Finish.
What's
next?
Understand the multiplatform project structure.
Create your first KMM application for Android and iOS – tutorial.
Create a full-stack web app with Kotlin Multiplatform – hands-on tutorial.
Discover
your
project
Discover main parts of your multiplatform project:
Multiplatform plugin
Targets
Source sets
Compilations
Multiplatform
plugin
When you create a multiplatform project, the Project Wizard automatically applies the kotlin-multiplatform Gradle plugin in
the file build.gradle (.kts).
Kotlin
plugins {
kotlin("multiplatform") version "1.5.31"
}
468
Groovy
plugins {
id 'org.jetbrains.kotlin.multiplatform' version '1.5.31'
}
The kotlin-multiplatform plugin configures the project for creating an application or library to work on multiple platforms
and prepares it for building on these platforms.
In the file build.gradle (.kts), it creates the kotlin extension at the top level, which includes configuration for targets, source
sets, and dependencies.
Targets
A multiplatform project is aimed at multiple platforms that are represented by different targets. A target is part of the build
that is responsible for building, testing, and packaging the application for a specific platform, such as macOS, iOS, or
Android. See the list of supported platforms.
When you create a multiplatform project, targets are added to the kotlin block in the file build.gradle (build.gradle.kts).
kotlin {
jvm()
js {
browser {}
}
}
Source
sets
The project includes the directory src with Kotlin source sets, which are collections of Kotlin code files, along with their
resources, dependencies, and language settings. A source set can be used in Kotlin compilations for one or more target
platforms.
Each source set directory includes Kotlin code files (the kotlin directory) and resources. The Project Wizard creates default
source sets for the main and test compilations of the common code and all added targets.
469
Source sets
Source sets are added to the sourceSets block of the top-level kotlin block.
Kotlin
kotlin {
sourceSets {
val commonMain by getting { /* ... */ }
val commonTest by getting { /* ... */ }
val jvmMain by getting { /* ... */ }
val jvmTest by getting { /* ... */ }
val jsMain by getting { /* ... */ }
val jsTest by getting { /* ... */ }
}
}
470
Groovy
kotlin {
sourceSets {
commonMain { /* ... */}
commonTest { /* ... */}
jvmMain { /* ... */}
jvmTest { /* ... */ }
jsMain { /* ... */}
jsTest { /* ... */}
}
}
Source sets form a hierarchy, which is used for sharing the common code. In a source set shared among several targets,
you can use the platform-specific language features and dependencies that are available for all these targets.
For example, all Kotlin/Native features are available in the desktopMain source set, which targets the Linux (linuxX64),
Windows (mingwX64), and macOS (macosX64) platforms.
Hierarchical structure
Compilations
471
Each target can have one or more compilations, for example, for production and test purposes.
main and test compilations for JVM, JS, and Native targets.
Compilations
Each compilation has a default source set, which contains sources and dependencies specific to that compilation.
Share
code
on
platforms
With Kotlin Multiplatform, you can share the code using the mechanisms Kotlin provides:
Share code among all platforms used in your project. Use it for sharing the common business logic that applies to all
platforms.
Share code among some platforms included in your project but not all. You can reuse much of the code in similar
platforms using a hierarchical structure. You can use target shortcuts for common combinations of targets or create
the hierarchical structure manually.
If you need to access platform-specific APIs from the shared code, use the Kotlin mechanism of expected and actual
472
declarations.
Share
code
on
all
platforms
If you have business logic that is common for all platforms, you don’t need to write the same code for each platform
– just share it in the common source set.
All platform-specific source sets depend on the common source set by default. You don’t need to specify any
dependsOn relations manually for default source sets, such as jvmMain, macosX64Main, and others.
If you need to access platform-specific APIs from the shared code, use the Kotlin mechanism of expected and actual
declarations.
Share
code
on
similar
platforms
You often need to create several native targets 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 is for iOS ARM64
devices, the other is 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 the same. So iOS-specific code
could be shared between them.
Evidently, 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.
In this case, you can share code across native targets in your project using the hierarchical structure.
To enable the hierarchy structure support, add the following option to your gradle.properties.
473
kotlin.mpp.enableGranularSourceSetsMetadata=true
There are two ways you can create the hierarchical structure:
Use target shortcuts to easily create the hierarchy structure for common combinations of native targets.
Learn more about sharing code in libraries and using Native libraries in the hierarchical structure.
Due to a known issue, you won't be able to use IDE features, such as code completion and highlighting, for the
shared native source set in a multiplatform project with hierarchical structure support if your project depends
on:
Third-party native libraries, with the exception of platform libraries supported out of the box.
This issue applies only to the shared native source set. The IDE will correctly support the rest of the code.
Learn how to work around this issue for similar source sets, such as iosArm64 and iosX64.
Use
target
shortcuts
In a typical multiplatform project with two iOS-related targets – iosArm64 and iosX64, the hierarchical structure includes
an intermediate source set (iosMain), which is used by the platform-specific source sets.
474
Code shared for iOS targets
The kotlin-multiplatform plugin provides target shortcuts for creating structures for common combinations of targets.
All shortcuts create similar hierarchical structures in the code. For example, the ios shortcut creates the following
hierarchical structure:
Kotlin
kotlin {
475
sourceSets{
val commonMain by sourceSets.getting
val iosX64Main by sourceSets.getting
val iosArm64Main by sourceSets.getting
val iosMain by sourceSets.creating {
dependsOn(commonMain)
iosX64Main.dependsOn(this)
iosArm64Main.dependsOn(this)
}
}
}
Groovy
kotlin {
sourceSets{
iosMain {
dependsOn(commonMain)
iosX64Main.dependsOn(it)
iosArm64Main.dependsOn(it)
}
}
}
2. Connect the simulator target with the shortcut using the source set dependencies (dependsOn).
Kotlin
kotlin {
ios()
// Add the ARM64 simulator target
iosSimulatorArm64()
val iosMain by sourceSets.getting
val iosTest by sourceSets.getting
val iosSimulatorArm64Main by sourceSets.getting
val iosSimulatorArm64Test by sourceSets.getting
Groovy
476
kotlin {
ios()
// Add the ARM64 simulator target
iosSimulatorArm64()
Configure
the
hierarchical
structure
manually
To create the hierarchical structure manually, introduce an intermediate source set that holds the shared code for several
targets and create a structure of the source sets including the intermediate one.
Hierarchical structure
For example, if you want to share code among native Linux, Windows, and macOS targets – linuxX64M, mingwX64, and
macosX64:
1. Add the intermediate source set desktopMain that holds the shared logic for these targets.
477
2. Specify the hierarchy of source sets using the dependsOn relation.
Kotlin
kotlin{
sourceSets {
val desktopMain by creating {
dependsOn(commonMain)
}
val linuxX64Main by getting {
dependsOn(desktopMain)
}
val mingwX64Main by getting {
dependsOn(desktopMain)
}
val macosX64Main by getting {
dependsOn(desktopMain)
}
}
}
Groovy
kotlin {
sourceSets {
desktopMain {
dependsOn(commonMain)
}
linuxX64Main {
dependsOn(desktopMain)
}
mingwX64Main {
dependsOn(desktopMain)
}
macosX64Main {
dependsOn(desktopMain)
}
}
}
You can have a shared source set for the following combinations of targets:
JVM + JS + Native
JVM + Native
JS + Native
JVM + JS
Native
Kotlin doesn’t currently support sharing a source set for these combinations:
478
Several JVM targets
Several JS targets
If you need to access platform-specific APIs from a shared native source set, IntelliJ IDEA will help you detect common
declarations that you can use in the shared native code. For other cases, use the Kotlin mechanism of expected and
actual declarations.
Share
code
in
libraries
Thanks to the hierarchical project structure, libraries can also provide common APIs for a subset of targets. When a library
is published, the API of its intermediate source sets is embedded into the library artifacts along with information about the
project structure. When you use this library, the intermediate source sets of your project access only those APIs of the
library which are available to the targets of each source set.
For example, check out the following source set hierarchy from the kotlinx.coroutines repository:
The concurrent source set declares the function runBlocking and is compiled for the JVM and the native targets. Once the
kotlinx.coroutines library is updated and published with the hierarchical project structure, you can depend on it and call
runBlocking from a source set that is shared between the JVM and native targets since it matches the “targets
signature†of the library’s concurrent source set.
479
Use
native
libraries
in
the
hierarchical
structure
You can use platform-dependent libraries like Foundation, UIKit, and POSIX in source sets shared among several native
targets. This helps you share more native code without being limited by platform-specific dependencies.
No additional steps are required – everything is done automatically. IntelliJ IDEA will help you detect common
declarations that you can use in the shared code.
To enable usage of platform-dependent libraries in shared source sets, add the following to your gradle.properties:
kotlin.mpp.enableGranularSourceSetsMetadata=true
kotlin.native.enableDependencyPropagation=false
In addition to platform libraries shipped with Kotlin/Native, this approach can also handle custom cinterop libraries
making them available in shared source sets. To enable this support, specify the additional
kotlin.mpp.enableCInteropCommonization key:
kotlin.mpp.enableCInteropCommonization=true
Connect
to
platform-specific
APIs
The expect/ actual feature is in Beta. It is almost stable, but migration steps may be required in the future. We'll
do our best to minimize any changes you will have to make.
If you’re developing a multiplatform application that needs to access platform-specific APIs that implement the
required functionality, use the Kotlin mechanism of expected and actual declarations.
With this mechanism, a common source set defines an expected declaration, and platform source sets must provide the
actual declaration that corresponds to the expected declaration. This works for most Kotlin declarations, such as
functions, classes, interfaces, enumerations, properties, and annotations.
480
Expect and actual declarations
// Common
expect fun randomUUID(): String
// Android
import java.util.*
actual fun randomUUID() = UUID.randomUUID().toString()
// iOS
import platform.Foundation.NSUUID
actual fun randomUUID(): String = NSUUID().UUIDString()
Here's another example of code sharing and interaction between the common and platform logic in a minimalistic logging
framework.
// Common
enum class LogLevel {
DEBUG, WARN, ERROR
}
481
// JVM
internal actual fun writeLogMessage(message: String, logLevel: LogLevel) {
println("[$logLevel]: $message")
}
For JavaScript, a completely different set of APIs is available, and the actual declaration will look like this.
// JS
internal actual fun writeLogMessage(message: String, logLevel: LogLevel) {
when (logLevel) {
LogLevel.DEBUG -> console.log(message)
LogLevel.WARN -> console.warn(message)
LogLevel.ERROR -> console.error(message)
}
}
Rules
for
expected
and
actual
declarations
The main rules regarding expected and actual declarations are:
An expected declaration is marked with the expect keyword; the actual declaration is marked with the actual keyword.
expect and actual declarations have the same name and are located in the same package (have the same fully
qualified name).
During each platform compilation, the compiler ensures that every declaration marked with the expect keyword in the
common or intermediate source set has the corresponding declarations marked with the actual keyword in all platform
source sets. The IDE provides tools that help you create the missing actual declarations.
If you have a platform-specific library that you want to use in shared code while providing your own implementation for
another platform, you can provide a typealias to an existing class as the actual declaration:
482
Use expected and actual declarations only for Kotlin declarations that have platform-specific dependencies. It
is better to implement as much functionality as possible in the shared module even if doing so takes more time.
Don’t overuse expected and actual declarations – in some cases, an interface may be a better choice
because it is more flexible and easier to test.
Set
up
targets
manually
You can add targets when creating a project with the Project Wizard. If you need to add a target later, you can do this
manually using target presets for supported platforms.
kotlin {
jvm() // Create a JVM target with the default name 'jvm'
linuxX64() {
/* Specify additional settings for the 'linux' target here */
}
}
Each target can have one or more compilations. In addition to default compilations for test and production purposes, you
can create custom compilations.
Distinguish
several
targets
for
one
platform
You can have several targets for one platform in a multiplatform library. For example, these targets can provide the same
API but use different libraries during runtime, such as testing frameworks and logging solutions. Dependencies on such a
multiplatform library may fail to resolve because it isn’t clear which target to choose.
To solve this, mark the targets on both the library author and consumer sides with a custom attribute, which Gradle uses
during dependency resolution.
For example, consider a testing library that supports both JUnit and TestNG in the two targets. The library author needs to
add an attribute to both targets as follows:
Kotlin
kotlin {
jvm("junit") {
attributes.attribute(testFrameworkAttribute, "junit")
}
jvm("testng") {
483
attributes.attribute(testFrameworkAttribute, "testng")
}
}
Groovy
kotlin {
jvm('junit') {
attributes.attribute(testFrameworkAttribute, 'junit')
}
jvm('testng') {
attributes.attribute(testFrameworkAttribute, 'testng')
}
}
The consumer has to add the attribute to a single target where the ambiguity arises.
Add
dependencies
To add a dependency on a library, set a dependency of the required type (for example, implementation) in the
dependencies block in your Gradle build script.
Kotlin
kotlin {
sourceSets {
val commonMain by getting {
dependencies {
implementation("com.example:my-library:1.0")
}
}
}
}
Groovy
kotlin {
sourceSets {
commonMain {
dependencies {
implementation 'com.example:my-library:1.0'
}
}
}
}
484
Alternatively, you can set dependencies at the top level.
Dependency
on
the
standard
library
A dependency on a standard library (stdlib) in each source set is added automatically. The version of the standard library
is the same as the version of the kotlin-multiplatform plugin.
For platform-specific source sets, the corresponding platform-specific variant of the library is used, while a common
standard library is added to the rest. The Kotlin Gradle plugin will select the appropriate JVM standard library depending
on the kotlinOptions.jvmTarget compiler option of your Gradle build script
Set
dependencies
on
test
libraries
The kotlin.test API is available for multiplatform tests. When you create a multiplatform project, the Project Wizard
automatically adds test dependencies to common and platform-specific source sets.
If you didn’t use the Project Wizard to create your project, you can add the dependencies manually.
Set
a
dependency
on
a
kotlinx
library
If you use a kotlinx library and need a platform-specific dependency, you can use platform-specific variants of libraries
with suffixes such as -jvm or -js, for example, kotlinx-coroutines-core-jvm. You can also use the library base artifact name
instead – kotlinx-coroutines-core.
Kotlin
kotlin {
sourceSets {
val jvmMain by getting {
dependencies {
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core-jvm:1.5.2")
}
}
}
}
Groovy
kotlin {
sourceSets {
jvmMain {
dependencies {
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core-jvm:1.5.2'
485
}
}
}
}
If you use a multiplatform library and need to depend on the shared code, set the dependency only once in the shared
source set. Use the library base artifact name, such as kotlinx-coroutines-core or ktor-client-core.
Kotlin
kotlin {
sourceSets {
val commonMain by getting {
dependencies {
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.5.2")
}
}
}
}
Groovy
kotlin {
sourceSets {
commonMain {
dependencies {
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.5.2'
}
}
}
}
Configure
compilations
Kotlin multiplatform projects use compilations for producing artifacts. Each target can have one or more compilations, for
example, for production and test purposes.
main and test compilations for JVM, JS, and Native targets.
486
Compilations
If you need to compile something other than production code and unit tests, for example, integration or performance
tests, you can create a custom compilation.
Compilations for one target since one target can have multiple compilations.
A specific compilation.
See the list of compilation parameters and compiler options available for all or specific targets.
Configure
all
compilations
kotlin {
targets.all {
compilations.all {
kotlinOptions {
allWarningsAsErrors = true
}
}
}
}
487
Configure
compilations
for
one
target
Kotlin
kotlin {
targets.jvm.compilations.all {
kotlinOptions {
sourceMap = true
metaInfo = true
}
}
}
Groovy
kotlin {
jvm().compilations.all {
kotlinOptions {
sourceMap = true
metaInfo = true
}
}
}
Configure
one
compilation
Kotlin
kotlin {
jvm {
val main by compilations.getting {
kotlinOptions {
jvmTarget = "1.8"
}
}
}
}
Groovy
kotlin {
jvm().compilations.main {
kotlinOptions {
jvmTarget = "1.8"
}
}
}
488
Create
a
custom
compilation
If you need to compile something other than production code and unit tests, for example, integration or performance
tests, create a custom compilation.
For example, to create a custom compilation for integration tests of the jvm() target, add a new item to the compilations
collection.
For custom compilations, you need to set up all dependencies manually. The default source set of a custom
compilation does not depend on the commonMain and the commonTest source sets.
Kotlin
kotlin {
jvm() {
compilations {
val main by getting
val integrationTest by compilations.creating {
defaultSourceSet {
dependencies {
// Compile against the main compilation's compile classpath and outputs:
implementation(main.compileDependencyFiles + main.output.classesDirs)
implementation(kotlin("test-junit"))
/* ... */
}
}
// Create a test task to run the tests produced by this compilation:
tasks.register<Test>("integrationTest") {
// Run the tests with the classpath containing the compile dependencies
(including 'main'),
// runtime dependencies, and the outputs of this compilation:
classpath = compileDependencyFiles + runtimeDependencyFiles +
output.allOutputs
// Run only the tests from this compilation's outputs:
testClassesDirs = output.classesDirs
}
}
}
}
}
Groovy
kotlin {
jvm() {
compilations.create('integrationTest') {
defaultSourceSet {
dependencies {
def main = compilations.main
489
// Compile against the main compilation's compile classpath and outputs:
implementation(main.compileDependencyFiles + main.output.classesDirs)
implementation kotlin('test-junit')
/* ... */
}
}
// Create a test task to run the tests produced by this compilation:
tasks.register('jvmIntegrationTest', Test) {
// Run the tests with the classpath containing the compile dependencies
(including 'main'),
// runtime dependencies, and the outputs of this compilation:
classpath = compileDependencyFiles + runtimeDependencyFiles + output.allOutputs
// Run only the tests from this compilation's outputs:
testClassesDirs = output.classesDirs
}
}
}
}
You also need to create a custom compilation in other cases, for example, if you want to combine compilations for
different JVM versions in your final artifact, or you have already set up source sets in Gradle and want to migrate to a
multiplatform project.
Include
Java
sources
in
JVM
compilations
By default, the JVM target ignores Java sources and compiles only Kotlin source files.
To include Java sources in the compilations of the JVM target, explicitly enable the Java language support for the target:
490
Enable Java language support
kotlin {
jvm {
withJava()
}
}
This applies the Gradle java plugin and configures the target to cooperate with it.
The Java source files are placed in the child directories of the Kotlin source roots. For example, the paths are:
Due to current limitations, the Kotlin plugin replaces some tasks configured by the Java plugin:
The resources are processed by the equivalent tasks of the compilations instead of *ProcessResources tasks.
The publication of this target is handled by the Kotlin plugin and doesn't require steps that are specific for the Java
plugin.
491
Configure
interop
with
native
languages
Kotlin provides interoperability with native languages and DSL to configure this for a specific compilation.
Swift via Apple platforms (macOS, iOS, watchOS, Kotlin can use only Swift declarations marked with the @objc
Objective-C tvOS) attribute.
A compilation can interact with several native libraries. Configure interoperability in the cinterops block of the compilation
with available parameters.
Kotlin
kotlin {
linuxX64 { // Replace with a target you need.
compilations.getByName("main") {
val myInterop by cinterops.creating {
// Def-file describing the native API.
// The default path is src/nativeInterop/cinterop/<interop-name>.def
defFile(project.file("def-file.def"))
// Package to place the Kotlin API generated.
packageName("org.sample")
// Options to be passed to compiler by cinterop tool.
compilerOpts("-Ipath/to/headers")
// Directories to look for headers.
includeDirs.apply {
// Directories for header search (an equivalent of the -I<path> compiler
option).
allHeaders("path1", "path2")
// Additional directories to search headers listed in the 'headerFilter' def-
file option.
// -headerFilterAdditionalSearchPrefix command line option equivalent.
headerFilterOnly("path1", "path2")
}
// A shortcut for includeDirs.allHeaders.
includeDirs("include/directory", "another/directory")
}
val anotherInterop by cinterops.creating { /* ... */ }
}
}
}
492
Groovy
kotlin {
linuxX64 { // Replace with a target you need.
compilations.main {
cinterops {
myInterop {
// Def-file describing the native API.
// The default path is src/nativeInterop/cinterop/<interop-name>.def
defFile project.file("def-file.def")
// Package to place the Kotlin API generated.
packageName 'org.sample'
// Options to be passed to compiler by cinterop tool.
compilerOpts '-Ipath/to/headers'
// Directories for header search (an eqivalent of the -I<path> compiler
option).
includeDirs.allHeaders("path1", "path2")
// Additional directories to search headers listed in the 'headerFilter' def-
file option.
// -headerFilterAdditionalSearchPrefix command line option equivalent.
includeDirs.headerFilterOnly("path1", "path2")
// A shortcut for includeDirs.allHeaders.
includeDirs("include/directory", "another/directory")
}
anotherInterop { /* ... */ }
}
}
}
}
Compilation
for
Android
The compilations created for an Android target by default are tied to Android build variants: for each build variant, a Kotlin
compilation is created under the same name.
Then, for each Android source set compiled for each of the variants, a Kotlin source set is created under that source set
name prepended by the target name, like the Kotlin source set androidDebug for an Android source set debug and the
Kotlin target named android. These Kotlin source sets are added to the variants’ compilations accordingly.
The default source set commonMain is added to each production (application or library) variant's compilation. The
commonTest source set is similarly added to the compilations of unit test and instrumented test variants.
Annotation processing with kapt is also supported, but due to current limitations it requires that the Android target is
created before the kapt dependencies are configured, which needs to be done in a top-level dependencies block rather
than within Kotlin source set dependencies.
kotlin {
493
android { /* ... */ }
}
dependencies {
kapt("com.my.annotation:processor:1.0.0")
}
Compilation
of
the
source
set
hierarchy
Kotlin can build a source set hierarchy with the dependsOn relation.
Whenever jvmMain is compiled for a certain target, commonMain takes part in that compilation as well and is also
compiled into the same target binary form, such as JVM class files.
Sources of jvmMain 'see' the declarations of commonMain, including internal declarations, and also see the
dependencies of commonMain, even those specified as implementation dependencies.
jvmMain can contain platform-specific implementations for the expected declarations of commonMain.
The resources of commonMain are always processed and copied along with the resources of jvmMain.
494
Language settings are checked for consistency in the following ways:
jvmMain should set a languageVersion that is greater than or equal to that of commonMain.
jvmMain should enable all unstable language features that commonMain enables (there's no such requirement for
bugfix features).
Run
tests
By default, Kotlin supports running tests for JVM, JS, Android, Linux, Windows, macOS as well as iOS, watchOS, and
tvOS simulators. To run tests for other Kotlin/Native targets, you need to configure them manually in an appropriate
environment, emulator, or test framework.
Required
dependencies
The kotlin.test API is available for multiplatform tests. When you create a multiplatform project, the Project Wizard
automatically adds test dependencies to common and platform-specific source sets.
If you didn’t use the Project Wizard to create your project, you can add the dependencies manually.
Run
tests
for
one
or
more
targets
To run tests for all targets, run the check task.
To run tests for a particular target suitable for testing, run a test task <targetName>Test.
Test
shared
code
For testing shared code, you can use actual declarations in your tests.
class Proxy {
fun proxyHello() = hello()
}
495
You can use the following test in commonTest:
import kotlin.test.Test
import kotlin.test.assertTrue
class SampleTests {
@Test
fun testProxy() {
assertTrue(Proxy().proxyHello().isNotEmpty())
}
}
import kotlin.test.Test
import kotlin.test.assertTrue
class SampleTestsIOS {
@Test
fun testHello() {
assertTrue("iOS" in hello())
}
}
You can also learn how to create and run multiplatform tests in the Create and publish a multiplatform library – tutorial.
Publish
a
multiplatform
library
You can publish a multiplatform library to a Maven repository with the maven-publish Gradle plugin. Specify the group,
version, and the repositories where the library should be published. The plugin creates publications automatically.
plugins {
//...
id("maven-publish")
}
group = "com.example"
version = "1.0"
publishing {
repositories {
maven {
//...
}
}
}
Complete the tutorial on creating and publishing a multiplatform library to get hands-on experience.
496
Structure
of
publications
When used with maven-publish, the Kotlin plugin automatically creates publications for each target that can be built on
the current host, except for the Android target, which needs an additional step to configure publishing.
Publications of a multiplatform library include an additional root publication kotlinMultiplatform that stands for the whole
library and is automatically resolved to the appropriate platform-specific artifacts when added as a dependency to the
common source set. Learn more about adding dependencies.
This kotlinMultiplatform publication includes metadata artifacts and references the other publications as its variants.
Some repositories, such as Maven Central, require that the root module contains a JAR artifact without a
classifier, for example kotlinMultiplatform-1.0.jar.
The Kotlin Multiplatform plugin automatically produces the required artifact with the embedded metadata
artifacts.
This means you don't have to customize your build by adding an empty artifact to the root module of your
library to meet the repository’s requirements.
The kotlinMultiplatform publication may also need the sources and documentation artifacts if that is required by the
repository. In that case, add those artifacts by using artifact(...) in the publication's scope.
Avoid
duplicate
publications
To avoid duplicate publications of modules that can be built on several platforms (like JVM and JS), configure the
publishing tasks for these modules to run conditionally.
You can detect the platform in the script, introduce a flag such as isMainHost and set it to true for the main target
platform. Alternatively, you can pass the flag from an external source, for example, from CI configuration.
This simplified example ensures that publications are only uploaded when isMainHost=true is passed. This means that a
publication that can be published from multiple platforms will be published only once – from the main host.
Kotlin
kotlin {
jvm()
js()
mingwX64()
linuxX64()
val publicationsFromMainHost =
listOf(jvm(), js()).map { it.name } + "kotlinMultiplatform"
publishing {
publications {
matching { it.name in publicationsFromMainHost }.all {
val targetPublication = this@all
tasks.withType<AbstractPublishToMaven>()
.matching { it.publication == targetPublication }
497
.configureEach { onlyIf { findProperty("isMainHost") == "true" } }
}
}
}
}
Groovy
kotlin {
jvm()
js()
mingwX64()
linuxX64()
def publicationsFromMainHost =
[jvm(), js()].collect { it.name } + "kotlinMultiplatform"
publishing {
publications {
matching { it.name in publicationsFromMainHost }.all { targetPublication ->
tasks.withType(AbstractPublishToMaven)
.matching { it.publication == targetPublication }
.configureEach { onlyIf { findProperty("isMainHost") == "true" } }
}
}
}
}
By default, each publication includes a sources JAR that contains the sources used by the main compilation of the target.
Publish
an
Android
library
To publish an Android library, you need to provide additional configuration.
By default, no artifacts of an Android library are published. To publish artifacts produced by a set of Android variants,
specify the variant names in the Android target block:
kotlin {
android {
publishLibraryVariants("release", "debug")
}
}
The example works for Android libraries without product flavors. For a library with product flavors, the variant names also
contain the flavors, like fooBarDebug or fooBazRelease.
If the published variants have the same build type (for example, all of them are release or debug), they will be
compatible with any consumer build type.
If the published variants have different build types, then only the release variants will be compatible with consumer
498
build types that are not among the published variants. All other variants (such as debug) will only match the same build
type on the consumer side, unless the consumer project specifies the matching fallbacks.
If you want to make every published Android variant compatible with only the same build type used by the library
consumer, set this Gradle property: kotlin.android.buildTypeAttribute.keep=true.
You can also publish variants grouped by the product flavor, so that the outputs of the different build types are placed in a
single module, with the build type becoming a classifier for the artifacts (the release build type is still published with no
classifier). This mode is disabled by default and can be enabled as follows:
kotlin {
android {
publishLibraryVariantsGroupedByFlavor = true
}
}
It is not recommended that you publish variants grouped by the product flavor in case they have different
dependencies, as those will be merged into one dependencies list.
Create
and
publish
a
multiplatform
library
–
tutorial
In this tutorial, you will learn how to create a multiplatform library for JVM, JS, and Native platforms, write common tests
for all platforms, and publish the library to a local Maven repository.
This library converts raw data – strings and byte arrays – to the Base64 format. It can be used on Kotlin/JVM,
Kotlin/JS, and any available Kotlin/Native platform.
You will use different ways to implement the conversion to the Base64 format on different platforms:
You will also test your code using common tests, and then publish the library to your local Maven repository.
Set
up
the
environment
You can complete this tutorial on any operating system. Download and install the latest version of IntelliJ IDEA with the
latest Kotlin plugin.
499
Create
a
project
1. In IntelliJ IDEA, select File | New | Project.
3. Enter a project name, then in the Multiplatform section select Library as the project template.
The wizard will create a sample multiplatform library with the following structure:
500
Multiplatform library structure
Write
cross-platform
code
Define the classes and interfaces you are going to implement in the common code.
3. Define the Base64Encoder interface that converts bytes to the Base64 format:
package org.jetbrains.base64
interface Base64Encoder {
fun encode(src: ByteArray): ByteArray
}
4. Define the Base64Factory object to provide an instance of the Base64Encoder interface to the common code:
The factory object is marked with the expect keyword in the cross-platform code. For each platform, you should provide
an actual implementation of the Base64Factory object with the platform-specific encoder. Learn more about platform-
specific implementations.
501
Provide
platform-specific
implementations
Now you will create the actual implementations of the Base64Factory object for each platform:
JVM
JS
Native
JVM
1. In the jvmMain/kotlin directory, create the org.jetbrains.base64 package.
3. Provide a simple implementation of the Base64Factory object that delegates to the java.util.Base64 class:
package org.jetbrains.base64
import java.util.*
Pretty simple, right? You've provided a platform-specific implementation by using a straightforward delegation to a third-
party implementation.
JS
The JS implementation will be very similar to the JVM one.
3. Provide a simple implementation of the Base64Factory object that delegates to the btoa() function.
package org.jetbrains.base64
import kotlinx.browser.window
502
actual fun createEncoder(): Base64Encoder = JsBase64Encoder
}
Native
Unfortunately, there is no third-party implementation available for all Kotlin/Native targets, so you need to write it yourself.
package org.jetbrains.base64
503
}
return result.toByteArray()
}
}
Test
your
library
Now when you have actual implementations of the Base64Factory object for all platforms, it's time to test your
multiplatform library.
To save time on testing, you can write common tests that will be executed on all platforms instead of testing each
platform separately.
Prerequisites
Before writing tests, add the encodeToString method with the default implementation to the Base64Encoder interface,
which is defined in commonMain/kotlin/org/jetbrains/base64/Base64.kt. This implementation converts byte arrays to
strings, which are much easier to test.
interface Base64Encoder {
fun encode(src: ByteArray): ByteArray
You can also provide a more efficient implementation of this method for a specific platform, for example, for JVM in
jvmMain/kotlin/org/jetbrains/base64/Base64.kt:
One of the benefits of a multiplatform library is having a default implementation with optional platform-specific overrides.
Write
common
tests
Now you have a string-based API that you can cover with basic tests.
504
3. Add tests to this file:
package org.jetbrains.base64
import kotlin.test.Test
class Base64Test {
@Test
fun testEncodeToString() {
checkEncodeToString("Kotlin is awesome", "S290bGluIGlzIGF3ZXNvbWU=")
}
@Test
fun testPaddedStrings() {
checkEncodeToString("", "")
checkEncodeToString("1", "MQ==")
checkEncodeToString("22", "MjI=")
checkEncodeToString("333", "MzMz")
checkEncodeToString("4444", "NDQ0NA==")
}
./gradlew check
You can also run the check Gradle task by double-clicking it in the list of Gradle tasks.
The tests will run on all platforms (JVM, JS, and Native).
Add
platform-specific
tests
You can also add tests that will be run only for a specific platform. For example, you can add UTF-16 tests on JVM. Just
follow the same steps as for common tests, but create the Base64Test file in jvmTest/kotlin/org/jetbrains/base64:
package org.jetbrains.base64
import org.junit.Test
import kotlin.test.assertEquals
class Base64JvmTest {
@Test
505
fun testNonAsciiString() {
val utf8String = "Gödel"
val actual = Base64Factory.createEncoder().encodeToString(utf8String.toByteArray())
assertEquals("R8O2ZGVs", actual)
}
}
This test will automatically run on the JVM platform in addition to the common tests.
Publish
your
library
to
the
local
Maven
repository
Your multiplatform library is ready for publishing so that you can use it in other projects.
1. In the build.gradle(.kts) file, apply the maven-publish plugin and specify the group and version of your library:
Kotlin
plugins {
kotlin("multiplatform") version "1.5.31"
id("maven-publish")
}
group = "org.jetbrains.base64"
version = "1.0.0"
Groovy
plugins {
id 'org.jetbrains.kotlin.multiplatform' version '1.5.31'
id 'maven-publish'
}
group = 'org.jetbrains.base64'
version = '1.0.0'
2. In the Terminal, run the publishToMavenLocal Gradle task to publish your library to your local Maven repository:
./gradlew publishToMavenLocal
You can also run the publishToMavenLocal Gradle task by double-clicking it in the list of Gradle tasks.
506
Add
a
dependency
on
the
published
library
Now you can add your library to other multiplatform projects as a dependency.
Add the mavenLocal() repository and add a dependency on your library to the build.gradle(.kts) file.
Kotlin
repositories {
mavenCentral()
mavenLocal()
}
kotlin {
sourceSets {
val commonMain by getting {
dependencies {
implementation("org.jetbrains.base64:Base64:1.0.0")
}
}
}
}
Groovy
repositories {
mavenCentral()
mavenLocal()
}
kotlin {
sourceSets {
commonMain {
dependencies {
implementation 'org.jetbrains.base64:Base64:1.0.0'
}
}
}
}
Summary
In this tutorial, you:
507
What’s
next?
Learn more about publishing multiplatform libraries.
Create your first KMM application for Android and iOS – tutorial.
Create a full-stack web app with Kotlin Multiplatform – hands-on tutorial.
Build
final
native
binaries
By default, a Kotlin/Native target is compiled down to a *.klib library artifact, which can be consumed by Kotlin/Native
itself as a dependency but cannot be executed or used as a native library.
To declare final native binaries such as executables or shared libraries, use the binaries property of a native target. This
property represents a collection of native binaries built for this target in addition to the default *.klib artifact and provides a
set of methods for declaring and configuring them.
The kotlin-multiplatform plugin doesn't create any production binaries by default. The only binary available by
default is a debug test executable that lets you run unit tests from the test compilation.
Declare
binaries
Use the following factory methods to declare elements of the binaries collection.
sharedLib Shared native library All native targets, except for WebAssembly
staticLib Static native library All native targets, except for WebAssembly
framework Objective-C framework macOS, iOS, watchOS, and tvOS targets only
The simplest version doesn't require any additional parameters and creates one binary for each build type. Currently, two
build types are available:
508
RELEASE – produces an optimized binary without debug information
The following snippet creates two executable binaries: debug and release.
kotlin {
linuxX64 { // Use your target instead.
binaries {
executable {
// Binary configuration.
}
}
}
}
You can drop the lambda if there is no need for additional configuration:
binaries {
executable()
}
You can specify for which build types to create binaries. In the following example, only the debug executable is created.
Kotlin
binaries {
executable(listOf(DEBUG)) {
// Binary configuration.
}
}
Groovy
binaries {
executable([DEBUG]) {
// Binary configuration.
}
}
Kotlin
binaries {
executable("foo", listOf(DEBUG)) {
// Binary configuration.
}
// It's possible to drop the list of build types (in which case, all the available build
types will be used).
509
executable("bar") {
// Binary configuration.
}
}
Groovy
binaries {
executable('foo', [DEBUG]) {
// Binary configuration.
}
// It's possible to drop the list of build types (in which case, all the available build
types will be used).
executable('bar') {
// Binary configuration.
}
}
The first argument sets a name prefix, which is the default name for the binary file. For example, for Windows the code
produces the files foo.exe and bar.exe. You can also use the name prefix to access the binary in the build script.
Access
binaries
You can access binaries to configure them or get their properties (for example, the path to an output file).
You can get a binary by its unique name. This name is based on the name prefix (if it is specified), build type, and binary
kind following the pattern: <optional-name-prefix><build-type><binary-kind>, for example, releaseFramework or
testDebugExecutable.
Static and shared libraries have the suffixes static and shared respectively, for example, fooDebugStatic or
barReleaseShared.
Kotlin
Groovy
510
binaries.fooDebugExecutable
binaries.getByName('fooDebugExecutable')
Alternatively, you can access a binary by its name prefix and build type using typed getters.
Kotlin
Groovy
Export
dependencies
to
binaries
When building an Objective-C framework or a native library (shared or static), you may need to pack not just the classes
of the current project, but also the classes of its dependencies. Specify which dependencies to export to a binary using
the export method.
Kotlin
kotlin {
511
sourceSets {
macosMain.dependencies {
// Will be exported.
api(project(":dependency"))
api("org.example:exported-library:1.0")
// Will not be exported.
api("org.example:not-exported-library:1.0")
}
}
macosX64("macos").binaries {
framework {
export(project(":dependency"))
export("org.example:exported-library:1.0")
}
sharedLib {
// It's possible to export different sets of dependencies to different binaries.
export(project(':dependency'))
}
}
}
Groovy
kotlin {
sourceSets {
macosMain.dependencies {
// Will be exported.
api project(':dependency')
api 'org.example:exported-library:1.0'
// Will not be exported.
api 'org.example:not-exported-library:1.0'
}
}
macosX64("macos").binaries {
framework {
export project(':dependency')
export 'org.example:exported-library:1.0'
}
sharedLib {
// It's possible to export different sets of dependencies to different binaries.
export project(':dependency')
}
}
}
You can export only api dependencies of the corresponding source set.
You can export maven dependencies, but due to current limitations of Gradle metadata, such a dependency
should be either a platform dependency (for example, kotlinx-coroutines-core-native_debug_macos_x64
instead of kotlinx-coroutines-core-native) or be exported transitively.
By default, export works non-transitively. This means that if you export the library foo depending on the library bar, only
methods of foo are added to the output framework.
512
You can change this behavior using the transitiveExport option. If set to true, the declarations of the library bar are
exported as well.
Kotlin
binaries {
framework {
export(project(":dependency"))
// Export transitively.
transitiveExport = true
}
}
Groovy
binaries {
framework {
export project(':dependency')
// Export transitively.
transitiveExport = true
}
}
For example, assume that you write several modules in Kotlin and then want to access them from Swift. Since usage of
several Kotlin/Native frameworks in one Swift application is limited, you can create a single umbrella framework and
export all these modules to it.
Build
universal
frameworks
By default, an Objective-C framework produced by Kotlin/Native supports only one platform. However, you can merge
such frameworks into a single universal (fat) binary using the lipo tool. This operation especially makes sense for 32-bit
and 64-bit iOS frameworks. In this case, you can use the resulting universal framework on both 32-bit and 64-bit devices.
The fat framework must have the same base name as the initial frameworks.
Kotlin
import org.jetbrains.kotlin.gradle.tasks.FatFrameworkTask
kotlin {
// Create and configure the targets.
val ios32 = iosArm32("ios32")
val ios64 = iosArm64("ios64")
configure(listOf(ios32, ios64)) {
binaries.framework {
baseName = "my_framework"
513
}
}
// Create a task to build a fat framework.
tasks.register<FatFrameworkTask>("debugFatFramework") {
// The fat framework must have the same base name as the initial frameworks.
baseName = "my_framework"
// The default destination directory is "<build directory>/fat-framework".
destinationDir = buildDir.resolve("fat-framework/debug")
// Specify the frameworks to be merged.
from(
ios32.binaries.getFramework("DEBUG"),
ios64.binaries.getFramework("DEBUG")
)
}
}
Groovy
import org.jetbrains.kotlin.gradle.tasks.FatFrameworkTask
kotlin {
// Create and configure the targets.
targets {
iosArm32("ios32")
iosArm64("ios64")
configure([ios32, ios64]) {
binaries.framework {
baseName = "my_framework"
}
}
}
// Create a task building a fat framework.
tasks.register("debugFatFramework", FatFrameworkTask) {
// The fat framework must have the same base name as the initial frameworks.
baseName = "my_framework"
// The default destination directory is "<build directory>/fat-framework".
destinationDir = file("$buildDir/fat-framework/debug")
// Specify the frameworks to be merged.
from(
targets.ios32.binaries.getFramework("DEBUG"),
targets.ios64.binaries.getFramework("DEBUG")
)
}
}
Build
XCFrameworks
All Kotlin Multiplatform projects can use XCFrameworks as an output to gather logic for all the target platforms and
architectures in a single bundle. Unlike universal (fat) frameworks, you don't need to remove all unnecessary architectures
before publishing the application to the App Store.
Kotlin
514
import org.jetbrains.kotlin.gradle.plugin.mpp.apple.XCFramework
plugins {
kotlin("multiplatform")
}
kotlin {
val xcf = XCFramework()
ios {
binaries.framework {
baseName = "shared"
xcf.add(this)
}
}
watchos {
binaries.framework {
baseName = "shared"
xcf.add(this)
}
}
tvos {
binaries.framework {
baseName = "shared"
xcf.add(this)
}
}
}
Groovy
import org.jetbrains.kotlin.gradle.plugin.mpp.apple.XCFrameworkConfig
plugins {
id 'org.jetbrains.kotlin.multiplatform'
}
kotlin {
def xcf = XCFrameworkConfig(project)
ios {
binaries.framework {
baseName = "shared"
xcf.add(it)
}
}
watchos {
binaries.framework {
baseName = "shared"
xcf.add(it)
}
}
tvos {
binaries.framework {
baseName = "shared"
xcf.add(it)
}
}
515
}
When you declare XCFrameworks, Kotlin Gradle plugin will register three Gradle tasks:
assembleXCFramework
assembleReleaseXCFramework
Supported
platforms
Kotlin supports the following platforms and provides target presets for each platform. See how to use a target preset.
Kotlin/JVM jvm
Android NDK androidNativeArm32, androidNativeArm64 The 64-bit target requires a Linux or macOS host.
516
Target platform Target preset Comments
Linux linuxArm64, linuxArm32Hfp, linuxMips32, Linux MIPS targets (linuxMips32 and linuxMipsel32)
linuxMipsel32, linuxX64
require a Linux host.
WebAssembly wasm32
A target that is not supported by the current host is ignored during building and therefore not published.
Multiplatform
Gradle
DSL
reference
Multiplatform projects are in Alpha. Language features and tooling may change in future Kotlin versions.
The Kotlin Multiplatform Gradle plugin is a tool for creating Kotlin multiplatform projects. Here we provide a reference of
its contents; use it as a reminder when writing Gradle build scripts for Kotlin multiplatform projects. Learn the concepts of
Kotlin multiplatform projects, how to create and configure them.
Id
and
version
The fully qualified name of the Kotlin Multiplatform Gradle plugin is org.jetbrains.kotlin.multiplatform. If you use the Kotlin
Gradle DSL, you can apply the plugin with kotlin(“multiplatformâ€). The plugin versions match the Kotlin release
versions. The most recent version is 1.5.31.
Kotlin
plugins {
kotlin("multiplatform") version "1.5.31"
}
517
Groovy
plugins {
id 'org.jetbrains.kotlin.multiplatform' version '1.5.31'
}
Top-level
blocks
kotlin is the top-level block for multiplatform project configuration in the Gradle build script. Inside kotlin, you can write the
following blocks:
Block Description
<targetName> Declares a particular target of a project. The names of available targets are listed in the Targets section.
presets All predefined targets. Use this for configuring multiple predefined targets at once.
sourceSets Configures predefined and declares custom source sets of the project.
Targets
Target is a part of the build responsible for compiling, testing, and packaging a piece of software aimed for one of the
supported platforms.
Each target can have one or more compilations. In addition to default compilations for test and production purposes, you
can create custom compilations.
The targets of a multiplatform project are described in the corresponding blocks inside kotlin, for example, jvm, android,
iosArm64. The complete list of available targets is the following:
Name Description
js JavaScript
518
Name Description
iosArm32 Apple iOS on ARM (ARM32) platforms (Apple iPhone 5 and earlier)
watchosArm32 Apple watchOS on ARM (ARM32) platforms (Apple Watch Series 3 and earlier)
watchosArm64 Apple watchOS on ARM64_32 platforms (Apple Watch Series 4 and newer)
watchosX86 Apple watchOS 32-bit simulator (watchOS 6.3 and earlier) on x86_64 platforms
watchosX64 Apple watchOS 64-bit simulator (watchOS 7.0 and newer) on x86_64 platforms
tvosArm64 Apple tvOS on ARM64 platforms (Apple TV 4th generation and newer)
519
Name Description
wasm32 WebAssembly
kotlin {
jvm()
iosX64()
macosX64()
js().browser()
}
Target-specific configuration.
Common
target
configuration
In any target block, you can use the following declarations:
Name Description
preset The preset that the target has been created from, if any.
platformType Designates the Kotlin platform of this target. Avaiable values: jvm, androidJvm, js, native, common.
artifactsTaskName The name of the task that builds the resulting artifacts of this target.
JVM
targets
In addition to common target configuration, jvm targets have a specific function:
520
Name Description
Use this function for projects that contain both Java and Kotlin source files. Note that the default source directories for
Java sources don't follow the Java plugin's defaults. Instead, they are derived from the Kotlin source sets. For example, if
the JVM target has the default name jvm, the paths are src/jvmMain/java (for production Java sources) and
src/jvmTest/java for test Java sources. Learn how to include Java sources in JVM compilations.
kotlin {
jvm {
withJava()
}
}
JavaScript
targets
The js block describes the configuration of JavaScript targets. It can contain one of two blocks depending on the target
execution environment:
Name Description
Browser
browser can contain the following configuration blocks:
Name Description
521
kotlin {
js().browser {
webpackTask { /* ... */ }
testRuns { /* ... */ }
dceTask {
keep("myKotlinJsApplication.org.example.keepFromDce")
}
distribution {
directory = File("$projectDir/customdir/")
}
}
}
Node.js
nodejs can contain configurations of test and run tasks:
Name Description
kotlin {
js().nodejs {
runTask { /* ... */ }
testRuns { /* ... */ }
}
}
Native
targets
For native targets, the following specific blocks are available:
Name Description
Binaries
There are the following kinds of binaries:
Name Description
522
Name Description
kotlin {
linuxX64 { // Use your target instead.
binaries {
executable {
// Binary configuration.
}
}
}
}
Name Description
compilation The compilation from which the binary is built. By default, test binaries are based on the test compilation while
other binaries - on the main compilation.
baseName Custom base name for the output file. The final file name will be formed by adding system-dependent prefix and
postfix to this base name.
entryPoint The entry point function for executable binaries. By default, it's main() in the root package.
runTask Access to the run task for executable binaries. For targets other than linuxX64, macosX64, or mingwX64 the
value is null.
isStatic For Objective-C frameworks. Includes a static library instead of a dynamic one.
523
Kotlin
binaries {
executable("my_executable", listOf(RELEASE)) {
// Build a binary on the basis of the test compilation.
compilation = compilations["test"]
framework("my_framework" listOf(RELEASE)) {
// Include a static library instead of a dynamic one into the framework.
isStatic = true
}
}
Groovy
binaries {
executable('my_executable', [RELEASE]) {
// Build a binary on the basis of the test compilation.
compilation = compilations.test
524
}
framework('my_framework' [RELEASE]) {
// Include a static library instead of a dynamic one into the framework.
isStatic = true
}
}
CInterops
cinterops is a collection of descriptions for interop with native libraries. To provide an interop with a library, add an entry
to cinterops and define its parameters:
Name Description
Kotlin
kotlin {
linuxX64 { // Replace with a target you need.
compilations.getByName("main") {
val myInterop by cinterops.creating {
// Def-file describing the native API.
// The default path is src/nativeInterop/cinterop/<interop-name>.def
defFile(project.file("def-file.def"))
// Directories for header search (an analogue of the -I<path> compiler option).
includeDirs.allHeaders("path1", "path2")
525
}
}
}
Groovy
kotlin {
linuxX64 { // Replace with a target you need.
compilations.main {
cinterops {
myInterop {
// Def-file describing the native API.
// The default path is src/nativeInterop/cinterop/<interop-name>.def
defFile project.file("def-file.def")
anotherInterop { /* ... */ }
}
}
}
}
Android
targets
The Kotlin multiplatform plugin contains two specific functions for android targets. Two functions help you configure build
variants:
Name Description
publishLibraryVariants() Specifies build variants to publish. Learn more about publishing Android libraries.
kotlin {
android {
publishLibraryVariants("release", "debug")
}
}
526
Learn more about compilation for Android.
The android configuration inside kotlin doesn’t replace the build configuration of any Android project. Learn
more about writing build scripts for Android projects in Android developer documentation.
Source
sets
The sourceSets block describes source sets of the project. A source set contains Kotlin source files that participate in
compilations together, along with their resources, dependencies, and language settings.
A multiplatform project contains predefined source sets for its targets; developers can also create custom source sets for
their needs.
Predefined
source
sets
Predefined source sets are set up automatically upon creation of a multiplatform project. Available predefined source sets
are the following:
Name Description
commonMain Code and resources shared between all platforms. Available in all multiplatform projects. Used in all main
compilations of a project.
commonTest Test code and resources shared between all platforms. Available in all multiplatform projects. Used in all
test compilations of a project.
<targetName> Target-specific sources for a compilation. <targetName> is the name of a predefined target and
<compilationName> <compilationName> is the name of a compilation for this target. Examples: jsTest, jvmMain.
With Kotlin Gradle DSL, the sections of predefined source sets should be marked by getting.
Kotlin
kotlin {
sourceSets {
val commonMain by getting { /* ... */ }
}
}
Groovy
kotlin {
sourceSets {
commonMain { /* ... */ }
}
527
}
Custom
source
sets
Custom source sets are created by the project developers manually. To create a custom source set, add a section with its
name inside the sourceSets section. If using Kotlin Gradle DSL, mark custom source sets by creating.
Kotlin
kotlin {
sourceSets {
val myMain by creating { /* ... */ } // create a new source set by the name 'MyMain'
}
}
Groovy
kotlin {
sourceSets {
myMain { /* ... */ } // create or configure a source set by the name 'myMain'
}
}
Note that a newly created source set isn’t connected to other ones. To use it in the project’s compilations,
connect it with other source sets.
Source
set
parameters
Configurations of source sets are stored inside the corresponding blocks of sourceSets. A source set has the following
parameters:
Name Description
kotlin.srcDir Location of Kotlin source files inside the source set directory.
528
Kotlin
kotlin {
sourceSets {
val commonMain by getting {
kotlin.srcDir("src")
resources.srcDir("res")
dependencies {
/* ... */
}
}
}
}
Groovy
kotlin {
sourceSets {
commonMain {
kotlin.srcDir('src')
resources.srcDir('res')
dependencies {
/* ... */
}
}
}
}
Compilations
A target can have one or more compilations, for example, for production or testing. There are predefined compilations
that are added automatically upon target creation. You can additionally create custom compilations.
To refer to all or some particular compilations of a target, use the compilations object collection. From compilations, you
can refer to a compilation by its name.
Predefined
compilations
Predefined compilations are created automatically for each target of a project except for Android targets. Available
predefined compilations are the following:
Name Description
529
Name Description
Kotlin
kotlin {
jvm {
val main by compilations.getting {
output // get the main compilation output
}
compilations["test"].runtimeDependencyFiles // get the test runtime classpath
}
}
Groovy
kotlin {
jvm {
compilations.main.output // get the main compilation output
compilations.test.runtimeDependencyFiles // get the test runtime classpath
}
}
Custom
compilations
In addition to predefined compilations, you can create your own custom compilations. To create a custom compilation,
add a new item into the compilations collection. If using Kotlin Gradle DSL, mark custom compilations by creating.
Kotlin
kotlin {
jvm() {
compilations {
val integrationTest by compilations.creating {
defaultSourceSet {
dependencies {
/* ... */
}
}
530
}
}
Groovy
kotlin {
jvm() {
compilations.create('integrationTest') {
defaultSourceSet {
dependencies {
/* ... */
}
}
Compilation
parameters
A compilation has the following parameters:
Name Description
allKotlinSourceSets Source sets participating in the compilation and their connections via dependsOn().
kotlinOptions Compiler options applied to the compilation. For the list of available options, see Compiler options.
compileAllTaskName Name of the Gradle task for compiling all sources of a compilation.
531
Kotlin
kotlin {
jvm {
val main by compilations.getting {
kotlinOptions {
// Setup the Kotlin compiler options for the 'main' compilation:
jvmTarget = "1.8"
}
compileKotlinTask // get the Kotlin task 'compileKotlinJvm'
output // get the main compilation output
}
compilations["test"].runtimeDependencyFiles // get the test runtime classpath
}
// Configure all compilations of all targets:
targets.all {
compilations.all {
kotlinOptions {
allWarningsAsErrors = true
}
}
}
}
Groovy
kotlin {
jvm {
compilations.main.kotlinOptions {
// Setup the Kotlin compiler options for the 'main' compilation:
jvmTarget = "1.8"
}
compilations.main.compileKotlinTask // get the Kotlin task 'compileKotlinJvm'
compilations.main.output // get the main compilation output
compilations.test.runtimeDependencyFiles // get the test runtime classpath
}
// Configure all compilations of all targets:
targets.all {
compilations.all {
kotlinOptions {
allWarningsAsErrors = true
}
}
}
}
Dependencies
The dependencies block of the source set declaration contains the dependencies of this source set.
532
Learn more about configuring dependencies.
Name Description
implementation Dependencies used in the module but not exposed outside it.
runtimeOnly Dependencies available at runtime but not visible during compilation of any module.
Kotlin
kotlin {
sourceSets {
val commonMain by getting {
dependencies {
api("com.example:foo-metadata:1.0")
}
}
val jvm6Main by getting {
dependencies {
implementation("com.example:foo-jvm6:1.0")
}
}
}
}
Groovy
kotlin {
sourceSets {
commonMain {
dependencies {
api 'com.example:foo-metadata:1.0'
}
}
jvm6Main {
dependencies {
implementation 'com.example:foo-jvm6:1.0'
}
}
}
}
Additionally, source sets can depend on each other and form a hierarchy. In this case, the dependsOn() relation is used.
533
Source set dependencies can also be declared in the top-level dependencies block of the build script. In this case, their
declarations follow the pattern <sourceSetName><DependencyKind>, for example, commonMainApi.
Kotlin
dependencies {
"commonMainApi"("com.example:foo-common:1.0")
"jvm6MainApi"("com.example:foo-jvm6:1.0")
}
Groovy
dependencies {
commonMainApi 'com.example:foo-common:1.0'
jvm6MainApi 'com.example:foo-jvm6:1.0'
}
Language
settings
The languageSettings block of a source set defines certain aspects of project analysis and build. The following language
settings are available:
Name Description
apiVersion Allows using declarations only from the specified version of Kotlin bundled libraries.
enableLanguageFeature Enables the specified language feature. The available values correspond to the language features
that are currently experimental or have been introduced as such at some point.
Kotlin
kotlin {
sourceSets.all {
languageSettings.apply {
languageVersion = "1.4" // possible values: "1.0", "1.1", "1.2", "1.3", "1.4"
apiVersion = "1.4" // possible values: "1.0", "1.1", "1.2", "1.3", "1.4"
enableLanguageFeature("InlineClasses") // language feature name
useExperimentalAnnotation("kotlin.ExperimentalUnsignedTypes") // annotation FQ-name
progressiveMode = true // false by default
534
}
}
}
Groovy
kotlin {
sourceSets.all {
languageSettings {
languageVersion = '1.4' // possible values: '1.0', '1.1', '1.2', '1.3', '1.4'
apiVersion = '1.4' // possible values: '1.0', '1.1', '1.2', '1.3', '1.4'
enableLanguageFeature('InlineClasses') // language feature name
useExperimentalAnnotation('kotlin.ExperimentalUnsignedTypes') // annotation FQ-name
progressiveMode = true // false by default
}
}
}
Migrating
multiplatform
projects
to
Kotlin
1.4.0
Kotlin 1.4.0 comes with lots of features and improvements in the tooling for multiplatform programming. Some of them
just work out of the box on existing projects, and some require additional configuration steps. This guide will help you
migrate your multiplatform projects to 1.4.0 or higher and get the benefits of all its new features.
For
multiplatform
project
authors
Update
Gradle
Starting with 1.4.0, Kotlin multiplatform projects require Gradle 6.0 or later. Make sure that your projects use the proper
version of Gradle and upgrade it if needed. See the Gradle documentation for non-Kotlin-specific migration instructions.
Simplify
your
build
configuration
Gradle module metadata provides rich publishing and dependency resolution features that are used in Kotlin
Multiplatform Projects. In Gradle 6.0 and above, module metadata is used in dependency resolution and included in
publications by default. Thus, once you update to such a version, you can remove
enableFeaturePreview("GRADLE_METADATA") from the project’s settings.gradle file.
If you use libraries published with metadata, you only have to specify dependencies on them only once in the shared
source set, as opposed to specifying dependencies on different variants of the same library in the shared and platform-
specific source sets prior to 1.4.0.
Starting from 1.4.0, you also no longer need to declare a dependency on stdlib in each source set manually – it will now
be added by default. The version of the automatically added standard library will be the same as the version of the Kotlin
Gradle plugin, since they have the same versioning.
535
With these features, you can make your Gradle build file much more concise and easy to read:
//...
android()
ios()
js()
sourceSets {
commonMain {
dependencies {
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:$coroutinesVersion")
}
}
}
//...
Don’t use kotlinx library artifact names with suffixes -common or -native, as they are no longer supported. Instead,
use the library root artifact name, which in the example above is kotlinx-coroutines-core.
Try
the
hierarchical
project
structure
With the new hierarchical project structure support, you can share code among several targets in a multiplatform project.
You can use platform-dependent libraries, such as Foundation, UIKit, and posix in source sets shared among several
native targets. This can help you share more native code without being limited by platform-specific dependencies.
By enabling the hierarchical structure along with its ability to use platform-dependent libraries in shared source sets, you
can eliminate the need to use certain workarounds to get IDE support for sharing source sets among several native
targets, for example iosArm64 and iosX64:
kotlin {
// workaround 1: select iOS target platform depending on the Xcode environment variables
val iOSTarget: (String, KotlinNativeTarget.() -> Unit) -> KotlinNativeTarget =
if (System.getenv("SDK_NAME")?.startsWith("iphoneos") == true)
::iosArm64
else
::iosX64
iOSTarget("ios")
}
# workaround 2: make symbolic links to use one source set for two targets
ln -s iosMain iosArm64Main && ln -s iosMain iosX64Main
Instead of doing this, you can create a hierarchical structure with target shortcuts available for typical multi-target
scenarios, or you can manually declare and connect the source sets. For example, you can create two iOS targets and a
shared source set with the ios() shortcut:
kotlin {
ios() // iOS device and simulator targets; iosMain and iosTest source sets
}
536
To enable the hierarchical project structure along with the use of platform-dependent libraries in shared source sets, just
add the following to your gradle.properties:
kotlin.mpp.enableGranularSourceSetsMetadata=true
kotlin.native.enableDependencyPropagation=false
In future versions, the hierarchical project structure will become default for Kotlin multiplatform project, so we strongly
encourage you to start using it now.
For
library
authors
Migrate
from
Gradle
Bintray
plugin
to
Maven
Publish
plugin
If you're using gradle-bintray-plugin for library publication, migrate your projects to maven-publish plugin instead. See
how we've done this for kotlinx.serialization. Learn more about publishing multiplatform libraries.
If for some reason you need to publish to Bintray and use the Gradle Bintray plugin, remember that this plugin doesn’t
support publishing Gradle module metadata. Use this workaround to fix this.
Follow
the
default
libraries’
layout
The layout of kotlinx libraries has changed and now corresponds to the default layout, which we recommend using: The
root or umbrella library module now has a name without a suffix (for example, kotlinx-coroutines-core instead of kotlinx-
coroutines-core-native). Publishing libraries with maven-publish Gradle plugin follows this layout by default. Learn more
about publishing multiplatform libraries.
Migrate
to
the
hierarchical
project
structure
A hierarchical project structure allows reusing code in similar targets, as well as publishing and consuming libraries with
granular APIs targeting similar platforms. We recommend that you switch to the hierarchical project structure in your
libraries when migrating to Kotlin 1.4.0 or higher:
By default, libraries published with the hierarchical project structure are compatible only with projects that have
hierarchical project structure. To enable compatibility with non-hierarchical projects, add the following to the
gradle.properties file in your library project:
kotlin.mpp.enableCompatibilityMetadataVariant=true
Libraries published without the hierarchical project structure can’t be used in a shared native source set. For
example, users with ios() shortcuts in their build.gradle.(kts) files won’t be able to use your library in their iOS-
shared code.
537
Library with hierarchical project Project with hierarchical project Compatibility
structure structure
No Yes ✅
In future versions, the hierarchical project structure with the usage of platform-dependent libraries in shared source sets
will be the default in multiplatform projects. So the sooner you support it, the sooner users will be able to migrate.
We’ll also be very grateful if you report any bugs you find to our issue tracker.
To enable hierarchical project structure support, add the following to your gradle.properties file:
kotlin.mpp.enableGranularSourceSetsMetadata=true
kotlin.mpp.enableCompatibilityMetadataVariant=true // to enable compatibility with projects
without hierarchical structure
For
build
authors
Check
task
names
The introduction of the hierarchical project structure in multiplatform projects resulted in a couple of changes to the
names of some Gradle tasks:
There are new compile<SourceSet>KotlinMetadata tasks for all published intermediate source sets.
These changes are relevant only for projects with the hierarchical project structure.
For
using
the
Kotlin/JS
target
Changes
related
to
npm
dependency
management
When declaring dependencies on npm packages, you are now required to explicitly specify a version or version range
based on npm’s semver syntax. Specifying multiple version ranges is also supported.
While we don’t recommend it, you can use a wildcard * in place of a version number if you do not want to specify a
538
version or version range explicitly.
Changes
related
to
the
Kotlin/JS
IR
compiler
Kotlin 1.4.0 introduces the Alpha IR compiler for Kotlin/JS. Learn more about the Kotlin/JS IR compiler’s backend and
how to configure it.
To choose between the different Kotlin/JS compiler options, set the key kotlin.js.compiler in your gradle.properties to
legacy, ir, or both. Alternatively, pass LEGACY, IR, or BOTH to the js function in your build.gradle(.kts).
kotlin {
js(IR) { // or: LEGACY, BOTH
// . . .
}
binaries.executable()
}
For backwards compatibility, when using the legacy compiler for Kotlin/JS, including or omitting binaries.executable() will
have no effect – executable files will be generated in either case. To make the legacy backend stop producing
executable files without the presence of binaries.executable() (for example, to improve build times where runnable
artifacts aren't required), set kotlin.js.generate.executable.default=false in your gradle.properties.
Changes
related
to
Dukat
The Dukat integration for Gradle has received minor naming and functionality changes with Kotlin 1.4.0.
The npm dependency function now takes a third parameter after the package name and version: generateExternals.
This allows you to individually control whether Dukat should generate declarations for a specific dependency, and it
overrides the generateKotlinExternals setting.
539
Using
artifacts
built
with
Kotlin
1.4.x
in
a
Kotlin
1.3.x
project
The choice between the IR and LEGACY compilers was not yet available in Kotlin 1.3.xx. Because of this, you may
encounter a Gradle error Cannot choose between the following variants... if one of your dependencies (or any transitive
dependency) was built using Kotlin 1.4+ but your project uses Kotlin 1.3.xx. A workaround is provided here.
Tutorials
for
Kotlin
Multiplatform
A number of tutorials are available to help you get acquainted with Kotlin Multiplatform. These tutorials come in two
varieties:
Plain tutorials describe how to complete a specific task from start to finish, with screenshots and code samples.
Creating your first KMM Tutorial Create a basic Kotlin Multiplatform Mobile (KMM) application using the KMM plugin for
application Android Studio.
Networking and data Hands- Create a KMM application for Android and iOS that will retrieve data over the internet from a
storage on public API, save it in a local database, and display it in a list in the application.
Creating and publishing Tutorial Create a multiplatform library that is available for JVM, JS, and Native, and that can be used
a multiplatform library from any other common code.
Building a full-stack web Hands- Create a client-server application that targets Kotlin/JVM and Kotlin/JS and uses common
application on code, serialization, and other multiplatform paradigms.
Get
started
with
Kotlin/JVM
This tutorial demonstrates how to use IntelliJ IDEA for creating a console application.
To get started, first download and install the latest version of IntelliJ IDEA.
Create
an
application
Once you've installed IntelliJ IDEA, it's time to create your first Kotlin application.
3. Enter a project name, select Console Application as the project template, and click Next.
540
Create a console application
By default, your project will use the Gradle build system with Kotlin DSL.
541
Your project will open. By default, you see the file build.gradle.kts, which is the build script created by the Project
Wizard based on your configuration. It includes the kotlin("jvm") plugin and dependencies required for your console
application.
6. Modify the code so that it requests your name and says Hello to you specifically, and not to the whole world.
Introduce a local variable name with the keyword val. It will get its value from an input where you will enter your
name – readLine().
Use a string template by adding a dollar sign $ before this variable name directly in the text output like this –
$name.
fun main() {
println("What's your name?")
val name= readLine()
println("Hello $name!")
}
542
Updated main fun
Run
the
application
Now the application is ready to run. The easiest way to do this is to click the green Run icon in the gutter and select Run
'MainKt'.
543
Kotlin run output
Enter your name and accept the greetings from your application!
What's
next?
Once you’ve created this application, you can start to dive deeper into Kotlin syntax:
Install the EduTools plugin for IDEA and complete exercises from the Kotlin Koans course
Comparison
to
Java
544
Some
Java
issues
addressed
in
Kotlin
Kotlin fixes a series of issues that Java suffers from:
No raw types
What
Java
has
that
Kotlin
does
not
Checked exceptions
Primitive types that are not classes. The byte-code uses primitives where possible, but they are not explicitly available.
Static members are replaced with companion objects, top-level functions, extension functions, or @JvmStatic.
What
Kotlin
has
that
Java
does
not
Lambda expressions + Inline functions = performant custom control structures
Extension functions
Null-safety
Smart casts
String templates
Properties
Primary constructors
First-class delegation
Singletons
545
Declaration-site variance & Type projections
Range expressions
Operator overloading
Companion objects
Data classes
Coroutines
What’s
next?
Learn how to perform typical tasks with strings in Java and Kotlin.
Calling
Java
from
Kotlin
Kotlin is designed with Java interoperability in mind. Existing Java code can be called from Kotlin in a natural way, and
Kotlin code can be used from Java rather smoothly as well. In this section, we describe some details about calling Java
code from Kotlin.
Pretty much all Java code can be used without any issues:
import java.util.*
Getters
and
setters
Methods that follow the Java conventions for getters and setters (no-argument methods with names starting with get and
single-argument methods with names starting with set) are represented as properties in Kotlin. Boolean accessor
methods (where the name of the getter starts with is and the name of the setter starts with set) are represented as
properties which have the same name as the getter method.
546
import java.util.Calendar
fun calendarDemo() {
val calendar = Calendar.getInstance()
if (calendar.firstDayOfWeek == Calendar.SUNDAY) { // call getFirstDayOfWeek()
calendar.firstDayOfWeek = Calendar.MONDAY // call setFirstDayOfWeek()
}
if (!calendar.isLenient) { // call isLenient()
calendar.isLenient = true // call setLenient()
}
}
Note that, if the Java class only has a setter, it isn't visible as a property in Kotlin because Kotlin doesn't support set-only
properties.
Methods
returning
void
If a Java method returns void, it will return Unit when called from Kotlin. If by any chance someone uses that return value,
it will be assigned at the call site by the Kotlin compiler since the value itself is known in advance (being Unit).
Escaping
for
Java
identifiers
that
are
keywords
in
Kotlin
Some of the Kotlin keywords are valid identifiers in Java: in, object, is, and other. If a Java library uses a Kotlin keyword
for a method, you can still call the method escaping it with the backtick (`) character:
foo.`is`(bar)
Null-safety
and
platform
types
Any reference in Java may be null, which makes Kotlin's requirements of strict null-safety impractical for objects coming
from Java. Types of Java declarations are treated in Kotlin in a specific manner and called platform types. Null-checks are
relaxed for such types, so that safety guarantees for them are the same as in Java (see more below).
When you call methods on variables of platform types, Kotlin does not issue nullability errors at compile time, but the call
may fail at runtime, because of a null-pointer exception or an assertion that Kotlin generates to prevent nulls from
propagating:
547
item.substring(1) // allowed, may throw an exception if item == null
Platform types are non-denotable, meaning that you can't write them down explicitly in the language. When a platform
value is assigned to a Kotlin variable, you can rely on the type inference (the variable will have an inferred platform type
then, as item has in the example above), or you can choose the type you expect (both nullable and non-null types are
allowed):
If you choose a non-null type, the compiler will emit an assertion upon assignment. This prevents Kotlin's non-null
variables from holding nulls. Assertions are also emitted when you pass platform values to Kotlin functions expecting non-
null values and in other cases. Overall, the compiler does its best to prevent nulls from propagating far through the
program although sometimes this is impossible to eliminate entirely, because of generics.
Notation
for
platform
types
As mentioned above, platform types can't be mentioned explicitly in the program, so there's no syntax for them in the
language. Nevertheless, the compiler and IDE need to display them sometimes (for example, in error messages or
parameter info), so there is a mnemonic notation for them:
(Mutable)Collection<T>! means "Java collection of T may be mutable or not, may be nullable or not",
Array<(out) T>! means "Java array of T (or a subtype of T), nullable or not"
Nullability
annotations
Java types that have nullability annotations are represented not as platform types, but as actual nullable or non-null Kotlin
types. The compiler supports several flavors of nullability annotations, including:
JSpecify (org.jspecify.nullness)
FindBugs (edu.umd.cs.findbugs.annotations)
Eclipse (org.eclipse.jdt.annotation)
Lombok (lombok.NonNull)
RxJava 3 (io.reactivex.rxjava3.annotations)
You can specify whether the compiler reports a nullability mismatch based on the information from specific types of
548
nullability annotations. Use the compiler option -Xnullability-annotations=@<package-name>:<report-level>. In the
argument, specify the fully qualified nullability annotations package and one of these report levels:
See the full list of supported nullability annotations in the Kotlin compiler source code.
Annotating
type
arguments
and
type
parameters
You can annotate the type arguments and type parameters of generic types to provide nullability information for them as
well.
All examples in the section use JetBrains nullability annotations from the org.jetbrains.annotations package.
Type arguments
Consider these annotations on a Java declaration:
@NotNull
Set<@NotNull String> toSet(@NotNull Collection<@NotNull String> elements) { ... }
When the @NotNull annotation is missing from a type argument, you get a platform type instead:
Kotlin also takes into account nullability annotations on type arguments of base classes and interfaces. For example,
there are two Java classes with the signatures provided below:
In the Kotlin code, passing the instance of Derived where the Base<String> is assumed produces the warning.
549
fun main() {
takeBaseOfNotNullStrings(Derived()) // warning: nullability mismatch
}
The upper bound of Derived is set to Base<String?>, which is different from Base<String>.
Type parameters
By default, the nullability of plain type parameters in both Kotlin and Java is undefined. In Java, you can specify it using
nullability annotations. Let's annotate the type parameter of the Base class:
When inheriting from Base, Kotlin expects a non-nullable type argument or type parameter. Thus, the following Kotlin
code produces a warning:
Kotlin also supports nullability annotations on the bounds of Java type parameters. Let's add bounds to Base:
Annotating type arguments and type parameters works with the Java 8 target or higher. The feature requires that the
nullability annotations support the TYPE_USE target (org.jetbrains.annotations supports this in version 15 and above).
Pass the -Xtype-enhancement-improvements-strict-mode compiler option to report errors in Kotlin code that uses
nullability which deviates from the nullability annotations from Java.
Note: If a nullability annotation supports other targets that are applicable to a type in addition to the TYPE_USE
target, then TYPE_USE takes priority. For example, if @Nullable has both TYPE_USE and METHOD targets, the
Java method signature @Nullable String[] f() becomes fun f(): Array<String?>! in Kotlin.
JSR-305
support
The @Nonnull annotation defined in JSR-305 is supported for denoting nullability of Java types.
550
If the @Nonnull(when = ...) value is When.ALWAYS, the annotated type is treated as non-null; When.MAYBE and
When.NEVER denote a nullable type; and When.UNKNOWN forces the type to be platform one.
A library can be compiled against the JSR-305 annotations, but there's no need to make the annotations artifact (e.g.
jsr305.jar) a compile dependency for the library consumers. The Kotlin compiler can read the JSR-305 annotations from a
library without the annotations present on the classpath.
@TypeQualifierNickname
@Nonnull(when = When.ALWAYS)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyNonnull {
}
@TypeQualifierNickname
@CheckForNull // a nickname to another type qualifier nickname
@Retention(RetentionPolicy.RUNTIME)
public @interface MyNullable {
}
interface A {
@MyNullable String foo(@MyNonnull String x);
// in Kotlin (strict mode): `fun foo(x: String): String?`
Such annotation type should itself be annotated with both @Nonnull (or its nickname) and @TypeQualifierDefault(...) with
one or more ElementType values:
ElementType.TYPE_USE for any type including type arguments, upper bounds of type parameters and wildcard types
The default nullability is used when a type itself is not annotated by a nullability annotation, and the default is determined
by the innermost enclosing element annotated with a type qualifier default annotation with the ElementType matching the
551
type usage.
@Nonnull
@TypeQualifierDefault({ElementType.METHOD, ElementType.PARAMETER})
public @interface NonNullApi {
}
@Nonnull(when = When.MAYBE)
@TypeQualifierDefault({ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE_USE})
public @interface NullableApi {
}
@NullableApi
interface A {
String foo(String x); // fun foo(x: String?): String?
The types in this example only take place with the strict mode enabled; otherwise, the platform types remain.
See the @UnderMigration annotation and Compiler configuration sections.
// FILE: test/package-info.java
@NonNullApi // declaring all types in package 'test' as non-nullable by default
package ;
@UnderMigration annotation
The @UnderMigration annotation (provided in a separate artifact kotlin-annotations-jvm) can be used by library
maintainers to define the migration status for the nullability type qualifiers.
The status value in @UnderMigration(status = ...) specifies how the compiler treats inappropriate usages of the annotated
types in Kotlin (e.g. using a @MyNullable -annotated type value as non-null):
MigrationStatus.STRICT makes annotation work as any plain nullability annotation, i.e. report errors for the
inappropriate usages and affect the types in the annotated declarations as they are seen in Kotlin
MigrationStatus.WARN: the inappropriate usages are reported as compilation warnings instead of errors, but the types
in the annotated declarations remain platform
552
MigrationStatus.IGNORE makes the compiler ignore the nullability annotation completely
A library maintainer can add @UnderMigration status to both type qualifier nicknames and type qualifier defaults:
@Nonnull(when = When.ALWAYS)
@TypeQualifierDefault({ElementType.METHOD, ElementType.PARAMETER})
@UnderMigration(status = MigrationStatus.WARN)
public @interface NonNullApi {
}
// The types in the class are non-null, but only warnings are reported
// because `@NonNullApi` is annotated `@UnderMigration(status = MigrationStatus.WARN)`
@NonNullApi
public class Test {}
The migration status of a nullability annotation is not inherited by its type qualifier nicknames but is applied to
its usages in default type qualifiers.
If a default type qualifier uses a type qualifier nickname and they are both @UnderMigration, the status from the default
type qualifier is used.
Compiler configuration
The JSR-305 checks can be configured by adding the -Xjsr305 compiler flag with the following options (and their
combination):
-Xjsr305={strict|warn|ignore} to set up the behavior for non- @UnderMigration annotations. Custom nullability qualifiers,
especially @TypeQualifierDefault, are already spread among many well-known libraries, and users may need to migrate
smoothly when updating to the Kotlin version containing JSR-305 support. Since Kotlin 1.1.60, this flag only affects
non- @UnderMigration annotations.
-Xjsr305=under-migration:{strict|warn|ignore} to override the behavior for the @UnderMigration annotations. Users may
have different view on the migration status for the libraries: they may want to have errors while the official migration
status is WARN, or vice versa, they may wish to postpone errors reporting for some until they complete their migration.
-Xjsr305=@<fq.name>:{strict|warn|ignore} to override the behavior for a single annotation, where <fq.name> is the fully
qualified class name of the annotation. May appear several times for different annotations. This is useful for managing
the migration state for a particular library.
The strict, warn and ignore values have the same meaning as those of MigrationStatus, and only the strict mode affects
the types in the annotated declarations as they are seen in Kotlin.
Note: the built-in JSR-305 annotations @Nonnull, @Nullable and @CheckForNull are always enabled and affect
the types of the annotated declarations in Kotlin, regardless of compiler configuration with the -Xjsr305 flag.
553
compiler arguments makes the compiler generate warnings for inappropriate usages of types annotated by
@org.library.MyNullable and ignore all other JSR-305 annotations.
The default behavior is the same to -Xjsr305=warn. The strict value should be considered experimental (more checks may
be added to it in the future).
Mapped
types
Kotlin treats some Java types specifically. Such types are not loaded from Java "as is", but are mapped to corresponding
Kotlin types. The mapping only matters at compile time, the runtime representation remains unchanged. Java's primitive
types are mapped to corresponding Kotlin types (keeping platform types in mind):
byte kotlin.Byte
short kotlin.Short
int kotlin.Int
long kotlin.Long
char kotlin.Char
float kotlin.Float
double kotlin.Double
boolean kotlin.Boolean
java.lang.Object kotlin.Any!
java.lang.Cloneable kotlin.Cloneable!
java.lang.Comparable kotlin.Comparable!
java.lang.Enum kotlin.Enum!
java.lang.Annotation kotlin.Annotation!
554
Java type Kotlin type
java.lang.CharSequence kotlin.CharSequence!
java.lang.String kotlin.String!
java.lang.Number kotlin.Number!
java.lang.Throwable kotlin.Throwable!
java.lang.Byte kotlin.Byte?
java.lang.Short kotlin.Short?
java.lang.Integer kotlin.Int?
java.lang.Long kotlin.Long?
java.lang.Character kotlin.Char?
java.lang.Float kotlin.Float?
java.lang.Double kotlin.Double?
java.lang.Boolean kotlin.Boolean?
Note that a boxed primitive type used as a type parameter is mapped to a platform type: for example,
List<java.lang.Integer> becomes a List<Int!> in Kotlin.
Collection types may be read-only or mutable in Kotlin, so Java's collections are mapped as follows (all Kotlin types in
this table reside in the package kotlin.collections):
Java type Kotlin read-only type Kotlin mutable type Loaded platform type
555
Java type Kotlin read-only type Kotlin mutable type Loaded platform type
int[] kotlin.IntArray!
The static members of these Java types are not directly accessible on the companion objects of the Kotlin
types. To call them, use the full qualified names of the Java types, e.g. java.lang.Integer.toHexString(foo).
Java
generics
in
Kotlin
Kotlin's generics are a little different from Java's (see Generics). When importing Java types to Kotlin, the following
conversions are done:
Like Java's, Kotlin's generics are not retained at runtime: objects do not carry information about actual type arguments
passed to their constructors. For example, ArrayList<Integer>() is indistinguishable from ArrayList<Character>(). This
makes it impossible to perform is -checks that take generics into account. Kotlin only allows is -checks for star-projected
generic types:
556
// but
if (a is List<*>) // OK: no guarantees about the contents of the list
Java
arrays
Arrays in Kotlin are invariant, unlike Java. This means that Kotlin won't let you assign an Array<String> to an Array<Any>,
which prevents a possible runtime failure. Passing an array of a subclass as an array of superclass to a Kotlin method is
also prohibited, but for Java methods this is allowed through platform types of the form Array<(out) String>!.
Arrays are used with primitive datatypes on the Java platform to avoid the cost of boxing/unboxing operations. As Kotlin
hides those implementation details, a workaround is required to interface with Java code. There are specialized classes
for every type of primitive array (IntArray, DoubleArray, CharArray, and so on) to handle this case. They are not related to
the Array class and are compiled down to Java's primitive arrays for maximum performance.
When compiling to the JVM bytecode, the compiler optimizes access to arrays so that there's no overhead introduced:
Even when you navigate with an index, it does not introduce any overhead:
557
Java
varargs
Java classes sometimes use a method declaration for the indices with a variable number of arguments (varargs):
In that case you need to use the spread operator * to pass the IntArray:
Operators
Since Java has no way of marking methods for which it makes sense to use the operator syntax, Kotlin allows using any
Java methods with the right name and signature as operator overloads and other conventions (invoke() etc.) Calling Java
methods using the infix call syntax is not allowed.
Checked
exceptions
In Kotlin, all exceptions are unchecked, meaning that the compiler does not force you to catch any of them. So, when you
call a Java method that declares a checked exception, Kotlin does not force you to do anything:
Object
methods
When Java types are imported into Kotlin, all the references of the type java.lang.Object are turned into Any. Since Any is
not platform-specific, it only declares toString(), hashCode() and equals() as its members, so to make other members of
java.lang.Object available, Kotlin uses extension functions.
558
wait()/notify()
Methods wait() and notify() are not available on references of type Any. Their usage is generally discouraged in favor of
java.util.concurrent. If you really need to call these methods, you can cast to java.lang.Object:
(foo as java.lang.Object).wait()
getClass()
To retrieve the Java class of an object, use the java extension property on a class reference:
The code above uses a bound class reference. You can also use the javaClass extension property:
clone()
To override clone(), your class needs to extend kotlin.Cloneable:
Don't forget about Effective Java, 3rd Edition, Item 13: Override clone judiciously.
finalize()
To override finalize(), all you need to do is simply declare it, without using the override keyword:
class C {
protected fun finalize() {
// finalization logic
}
}
Inheritance
from
Java
classes
At most one Java class (and as many Java interfaces as you like) can be a supertype for a class in Kotlin.
559
Accessing
static
members
Static members of Java classes form "companion objects" for these classes. You can't pass such a "companion object"
around as a value but can access the members explicitly, for example:
if (Character.isLetter(a)) { ... }
To access static members of a Java type that is mapped to a Kotlin type, use the full qualified name of the Java type:
java.lang.Integer.bitCount(foo).
Java
reflection
Java reflection works on Kotlin classes and vice versa. As mentioned above, you can use instance::class.java,
ClassName::class.java or instance.javaClass to enter Java reflection through java.lang.Class. Do not use
ClassName.javaClass for this purpose because it refers to ClassName 's companion object class, which is the same as
ClassName.Companion::class.java and not ClassName::class.java.
For each primitive type, there are two different Java classes, and Kotlin provides ways to get both. For example,
Int::class.java will return the class instance representing the primitive type itself, corresponding to Integer.TYPE in Java.
To get the class of the corresponding wrapper type, use Int::class.javaObjectType, which is equivalent of Java's
Integer.class.
Other supported cases include acquiring a Java getter/setter method or a backing field for a Kotlin property, a KProperty
for a Java field, a Java method or constructor for a KFunction and vice versa.
SAM
conversions
Kotlin supports SAM conversions for both Java and Kotlin interfaces. This support for Java means that Kotlin function
literals can be automatically converted into implementations of Java interfaces with a single non-default method, as long
as the parameter types of the interface method match the parameter types of the Kotlin function.
If the Java class has multiple methods taking functional interfaces, you can choose the one you need to call by using an
adapter function that converts a lambda to a specific SAM type. Those adapter functions are also generated by the
compiler when needed:
560
executor.execute(Runnable { println("This runs in a thread pool") })
SAM conversions only work for interfaces, not for abstract classes, even if those also have just a single abstract
method.
Using
JNI
with
Kotlin
To declare a function that is implemented in native (C or C++) code, you need to mark it with the external modifier:
The rest of the procedure works in exactly the same way as in Java.
Behind the scenes, this will create two functions getMyProperty and setMyProperty, both marked as external.
Using
Lombok-generated
declarations
in
Kotlin
You can use Java's Lombok-generated declarations in Kotlin code. If you need to generate and use these declarations in
the same mixed Java/Kotlin module, you can learn how to do this on the Lombok compiler plugin's page. If you call such
declarations from another module, then you don't need to use this plugin to compile that module.
Calling
Kotlin
from
Java
Kotlin code can be easily called from Java. For example, instances of a Kotlin class can be seamlessly created and
operated in Java methods. However, there are certain differences between Java and Kotlin that require attention when
integrating Kotlin code into Java. On this page, we'll describe the ways to tailor the interop of your Kotlin code with its
Java clients.
Properties
A Kotlin property is compiled to the following Java elements:
a getter method, with the name calculated by prepending the get prefix
561
a setter method, with the name calculated by prepending the set prefix (only for var properties)
a private field, with the same name as the property name (only for properties with backing fields)
For example, var firstName: String compiles to the following Java declarations:
If the name of the property starts with is, a different name mapping rule is used: the name of the getter will be the same
as the property name, and the name of the setter will be obtained by replacing is with set. For example, for a property
isOpen, the getter will be called isOpen() and the setter will be called setOpen(). This rule applies for properties of any
type, not just Boolean.
Package-level
functions
All the functions and properties declared in a file app.kt inside a package org.example, including extension functions, are
compiled into static methods of a Java class named org.example.AppKt.
// app.kt
package org.example
class Util
// Java
new Util();
AppKt.getTime();
To set a custom name to the generated Java class, use the @JvmName annotation:
@file:JvmName("DemoUtils")
package org.example
class Util
562
// Java
new Util();
DemoUtils.getTime();
Having multiple files with the same generated Java class name (the same package and the same name or the same
@JvmName annotation) is normally an error. However, the compiler can generate a single Java facade class which has
the specified name and contains all the declarations from all the files which have that name. To enable the generation of
such a facade, use the @JvmMultifileClass annotation in all such files.
// oldutils.kt
@file:JvmName("Utils")
@file:JvmMultifileClass
package org.example
// newutils.kt
@file:JvmName("Utils")
@file:JvmMultifileClass
package org.example
// Java
Utils.getTime();
Utils.getDate();
Instance
fields
If you need to expose a Kotlin property as a field in Java, annotate it with the @JvmField annotation. The field will have
the same visibility as the underlying property. You can annotate a property with @JvmField if it:
is not private
// Java
563
class JavaClient {
public String getID(User user) {
return user.ID;
}
}
Late-Initialized properties are also exposed as fields. The visibility of the field will be the same as the visibility of lateinit
property setter.
Static
fields
Kotlin properties declared in a named object or a companion object will have static backing fields either in that named
object or in the class containing the companion object.
Usually these fields are private but they can be exposed in one of the following ways:
@JvmField annotation
lateinit modifier
const modifier
Annotating such a property with @JvmField makes it a static field with the same visibility as the property itself.
// Java
Key.COMPARATOR.compare(key1, key2);
// public static final field in Key class
A late-initialized property in an object or a companion object has a static backing field with the same visibility as the
property setter.
object Singleton {
lateinit var provider: Provider
}
// Java
Singleton.provider = new Provider();
// public static non-final field in Singleton class
Properties declared as const (in classes as well as at the top level) are turned into static fields in Java:
564
// file example.kt
object Obj {
const val CONST = 1
}
class C {
companion object {
const val VERSION = 9
}
}
In Java:
Static
methods
As mentioned above, Kotlin represents package-level functions as static methods. Kotlin can also generate static
methods for functions defined in named objects or companion objects if you annotate those functions as @JvmStatic. If
you use this annotation, the compiler will generate both a static method in the enclosing class of the object and an
instance method in the object itself. For example:
class C {
companion object {
@JvmStatic fun callStatic() {}
fun callNonStatic() {}
}
}
object Obj {
@JvmStatic fun callStatic() {}
fun callNonStatic() {}
}
565
In Java:
Starting from Kotlin 1.3, @JvmStatic applies to functions defined in companion objects of interfaces as well. Such
functions compile to static methods in interfaces. Note that static method in interfaces were introduced in Java 1.8, so be
sure to use the corresponding targets.
interface ChatBot {
companion object {
@JvmStatic fun greet(username: String) {
println("Hello, $username")
}
}
}
@JvmStatic annotation can also be applied on a property of an object or a companion object making its getter and setter
methods static members in that object or the class containing the companion object.
Default
methods
in
interfaces
Default methods are available only for targets JVM 1.8 and above.
Starting from JDK 1.8, interfaces in Java can contain default methods. To make all non-abstract members of Kotlin
interfaces default for the Java classes implementing them, compile the Kotlin code with the -Xjvm-default=all compiler
option.
interface Robot {
fun move() { println("~walking~") } // will be default in the Java interface
fun speak(): Unit
}
The default implementation is available for Java classes implementing the interface.
//Java implementation
public class C3PO implements Robot {
// move() implementation from Robot is available implicitly
566
@Override
public void speak() {
System.out.println("I beg your pardon, sir");
}
}
//Java
public class BB8 implements Robot {
//own implementation of the default method
@Override
public void move() {
System.out.println("~rolling~");
}
@Override
public void speak() {
System.out.println("Beep-beep");
}
}
Prior to Kotlin 1.4, to generate default methods, you could use the @JvmDefault annotation on these methods.
Compiling with -Xjvm-default=all in 1.4+ generally works as if you annotated all non-abstract methods of
interfaces with @JvmDefault and compiled with -Xjvm-default=enable. However, there are cases when their
behavior differs. Detailed information about the changes in default methods generation in Kotlin 1.4 is provided
in this post on the Kotlin blog.
Compatibility
mode
for
default
methods
If there are clients that use your Kotlin interfaces compiled without the new -Xjvm-default=all option, then they can be
incompatible with the same code compiled with this option.
To avoid breaking the compatibility with such clients, compile your Kotlin code in the compatibility mode by specifying
the -Xjvm-default=all-compatibility compiler option. In this case, all the code that uses the previous version will work fine
with the new one. However, the compatibility mode adds some overhead to the resulting bytecode size.
There is no need to consider compatibility for new interfaces, as no clients have used them before. You can minimize the
compatibility overhead by excluding these interfaces from the compatibility mode. To do this, annotate them with the
@JvmDefaultWithoutCompatibility annotation. Such interfaces compile the same way as with -Xjvm-default=all.
Additionally, in the all-compatibility mode you can use @JvmDefaultWithoutCompatibility to annotate all interfaces which
are not exposed in the public API and therefore aren’t used by the existing clients.
567
Visibility
The Kotlin visibility modifiers map to Java in the following way:
protected remains protected (note that Java allows accessing protected members from other classes in the same
package and Kotlin doesn't, so Java classes will have broader access to the code)
internal declarations become public in Java. Members of internal classes go through name mangling, to make it harder
to accidentally use them from Java and to allow overloading for members with the same signature that don't see each
other according to Kotlin rules
KClass
Sometimes you need to call a Kotlin method with a parameter of type KClass. There is no automatic conversion from
Class to KClass, so you have to do it manually by invoking the equivalent of the Class<T>.kotlin extension property:
kotlin.jvm.JvmClassMappingKt.getKotlinClass(MainView.class)
Handling
signature
clashes
with
@JvmName
Sometimes we have a named function in Kotlin, for which we need a different JVM name in the bytecode. The most
prominent example happens due to type erasure:
These two functions can not be defined side-by-side, because their JVM signatures are the same:
filterValid(Ljava/util/List;)Ljava/util/List;. If we really want them to have the same name in Kotlin, we can annotate one (or
both) of them with @JvmName and specify a different name as an argument:
@JvmName("filterValidInt")
fun List<Int>.filterValid(): List<Int>
From Kotlin they will be accessible by the same name filterValid, but from Java it will be filterValid and filterValidInt.
The same trick applies when we need to have a property x alongside with a function getX():
568
val x: Int
@JvmName("getX_prop")
get() = 15
fun getX() = 10
To change the names of generated accessor methods for properties without explicitly implemented getters and setters,
you can use @get:JvmName and @set:JvmName:
@get:JvmName("x")
@set:JvmName("changeX")
var x: Int = 23
Overloads
generation
Normally, if you write a Kotlin function with default parameter values, it will be visible in Java only as a full signature, with
all parameters present. If you wish to expose multiple overloads to Java callers, you can use the @JvmOverloads
annotation.
The annotation also works for constructors, static methods, and so on. It can't be used on abstract methods, including
methods defined in interfaces.
class Circle @JvmOverloads constructor(centerX: Int, centerY: Int, radius: Double = 1.0) {
@JvmOverloads fun draw(label: String, lineWidth: Int = 1, color: String = "red") { /*...*/ }
}
For every parameter with a default value, this will generate one additional overload, which has this parameter and all
parameters to the right of it in the parameter list removed. In this example, the following will be generated:
// Constructors:
Circle(int centerX, int centerY, double radius)
Circle(int centerX, int centerY)
// Methods
void draw(String label, int lineWidth, String color) { }
void draw(String label, int lineWidth) { }
void draw(String label) { }
Note that, as described in Secondary constructors, if a class has default values for all constructor parameters, a public
constructor with no arguments will be generated for it. This works even if the @JvmOverloads annotation is not specified.
Checked
exceptions
Kotlin does not have checked exceptions. So, normally the Java signatures of Kotlin functions do not declare exceptions
thrown. Thus, if you have a function in Kotlin like this:
569
// example.kt
package demo
fun writeToFile() {
/*...*/
throw IOException()
}
And you want to call it from Java and catch the exception:
// Java
try {
Example.writeToFile();
} catch (IOException e) {
// error: writeToFile() does not declare IOException in the throws list
// ...
}
You get an error message from the Java compiler, because writeToFile() does not declare IOException. To work around
this problem, use the @Throws annotation in Kotlin:
@Throws(IOException::class)
fun writeToFile() {
/*...*/
throw IOException()
}
Null-safety
When calling Kotlin functions from Java, nobody prevents us from passing null as a non-null parameter. That's why Kotlin
generates runtime checks for all public functions that expect non-nulls. This way we get a NullPointerException in the
Java code immediately.
Variant
generics
When Kotlin classes make use of declaration-site variance, there are two options of how their usages are seen from the
Java code. For example, imagine you have the following class and two functions that use it:
interface Base
class Derived : Base
570
A naive way of translating these functions into Java would be this:
The problem is that in Kotlin you can write unboxBase(boxDerived(Derived())) but in Java that would be impossible
because in Java the class Box is invariant in its parameter T, and thus Box<Derived> is not a subtype of Box<Base>. To
make this work in Java, you would have to define unboxBase as follows:
This declaration uses Java's wildcards types (? extends Base) to emulate declaration-site variance through use-site
variance, because it is all Java has.
To make Kotlin APIs work in Java, the compiler generates Box<Super> as Box<? extends Super> for covariantly defined
Box (or Foo<? super Bar> for contravariantly defined Foo) when it appears as a parameter. When it's a return value,
wildcards are not generated, because otherwise Java clients will have to deal with them (and it's against the common
Java coding style). Therefore, the functions from our example are actually translated as follows:
When the argument type is final, there's usually no point in generating the wildcard, so Box<String> is always
Box<String>, no matter what position it takes.
If you need wildcards where they are not generated by default, use the @JvmWildcard annotation:
In the opposite case, if you don't need wildcards where they are generated, use @JvmSuppressWildcards:
@JvmSuppressWildcards can be used not only on individual type arguments, but on entire declarations, such
as functions or classes, causing all wildcards inside them to be suppressed.
571
Translation
of
type
Nothing
The type Nothing is special, because it has no natural counterpart in Java. Indeed, every Java reference type, including
java.lang.Void, accepts null as a value, and Nothing doesn't accept even that. So, this type cannot be accurately
represented in the Java world. This is why Kotlin generates a raw type where an argument of type Nothing is used:
Create
a
RESTful
web
service
with
a
database
using
Spring
Boot
–
tutorial
This tutorial walks you through the process of creating a simple application with Spring Boot and adding a database to
store the information.
You can download and explore the completed project or watch a video of this tutorial:
Gif
572
Before
you
start
Download and install the latest version of IntelliJ IDEA.
Bootstrap
the
project
Use Spring Initializr to create a new project:
You can also create a new project using IntelliJ IDEA with the Spring Boot plugin
1. Open Spring Initializr. This link opens the page with the project settings for this tutorial already filled in. This project
uses Gradle, Kotlin, Spring Web, Spring Data JDBC, and H2 Database:
2. Click GENERATE at the bottom of the screen. Spring Initializr will generate the project with the specified settings. The
download starts automatically.
573
The Spring Boot project structure
There are packages and classes under the main/kotlin folder that belong to the application. The entry point to the
application is the main() method of the DemoApplication.kt file.
Explore
the
project
build
file
Open the build.gradle.kts file.
This is the Gradle Kotlin build script, which contains a list of the dependencies required for the application.
The Gradle file is standard for Spring Boot, but it also contains necessary Kotlin dependencies, including the kotlin-spring
Gradle plugin.
574
Explore
the
Spring
Boot
application
Open the DemoApplication.kt file:
package demo
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
@SpringBootApplication
class DemoApplication
Note that the Kotlin application file differs from a Java application file:
While Spring Boot looks for a public static main() method, the Kotlin application uses a top-level function defined
outside DemoApplication class.
The DemoApplication class is not declared as open, since the kotlin-spring plugin does that automatically.
Create
a
data
class
and
a
controller
To create an endpoint, add a data class and a controller to your project:
1. In the DemoApplication.kt file, create a Message data class with two properties: id and text:
2. In the same file, create a MessageResource class which will serve the requests and return a JSON document
containing a collection of Message objects:
@RestController
class MessageResource {
@GetMapping
fun index(): List<Message> = listOf(
Message("1", "Hello!"),
Message("2", "Bonjour!"),
Message("3", "Privet!"),
)
}
package demo
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
575
import org.springframework.data.annotation.Id
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RestController
@SpringBootApplication
class DemoApplication
@RestController
class MessageResource {
@GetMapping
fun index(): List<Message> = listOf(
Message("1", "Hello!"),
Message("2", "Bonjour!"),
Message("3", "Privet!"),
)
}
Run
the
application
The application is now ready to run:
1. Click the green Run icon in the gutter beside the main() method or use the Alt+Enter shortcut to invoke the launch
menu in IntelliJ IDEA:
576
Run the application
You can also run the ./gradlew bootRun command in the terminal.
577
Application output
Add
database
support
To use a database in your application, first create two endpoints: one for saving messages and one for retrieving them:
1. Add the @Table annotation to the Message class to declare mapping to a database table. Add the @Id annotation
before the id field. These annotations also require additional imports:
import org.springframework.data.annotation.Id
import org.springframework.data.relational.core.mapping.Table
@Table("MESSAGES")
data class Message(@Id val id: String?, val text: String)
import org.springframework.data.jdbc.repository.query.Query
import org.springframework.data.repository.CrudRepository
When you call the findMessages() method on an instance of MessageRepository, it will execute the corresponding
database query:
This query retrieves a list of all Message objects in the database table.
import org.springframework.stereotype.Service
@Service
class MessageService(val db: MessageRepository) {
578
post() for writing a new Message object to the database
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.PostMapping
@RestController
class MessageResource(val service: MessageService) {
@GetMapping
fun index(): List<Message> = service.findMessages()
@PostMapping
fun post(@RequestBody message: Message) {
service.post(message)
}
}
Configure
the
database
Configure the database in the application:
1. Create a new folder called sql in the src/main/resources with the schema.sql file inside. It will store the database
scheme:
579
CREATE TABLE IF NOT EXISTS messages (
id VARCHAR(60) DEFAULT RANDOM_UUID() PRIMARY KEY,
text VARCHAR NOT NULL
);
It creates the messages table with two fields: id and text. The table structure matches the structure of the Message
class.
3. Open the application.properties file located in the src/main/resources folder and add the following application
properties:
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.url=jdbc:h2:file:./data/testdb
spring.datasource.username=sa
spring.datasource.password=password
spring.datasource.schema=classpath:sql/schema.sql
spring.datasource.initialization-mode=always
These settings enable the database for the Spring Boot application. See the full list of common application properties
in the Spring documentation.
Execute
HTTP
requests
You should use an HTTP client to work with previously created endpoints. In IntelliJ IDEA, you can use the embedded
HTTP client:
1. Run the application. Once the application is up and running, you can execute POST requests to store messages in the
database.
2. Create the requests.http file and add the following HTTP requests:
{
"text": "Hello!"
}
POST http://localhost:8080/
Content-Type: application/json
{
"text": "Bonjour!"
}
POST http://localhost:8080/
580
Content-Type: application/json
{
"text": "Privet!"
}
3. Execute all POST requests. Use the green Run icon in the gutter next to the request declaration. These requests write
the text messages to the database.
4. Execute the GET request and see the result in the Run tool window:
581
Run HTTP GET request
Alternative
way
to
execute
requests
You can also use any other HTTP client or cURL command-line tool. For example, you can run the following commands in
the terminal to get the same result:
What's
next?
For more tutorials, check out the Spring website:
582
Test
code
using
JUnit
in
JVM
–
tutorial
This tutorial will show you how to write a simple unit test and run it with the Gradle build tool.
The example in the tutorial has the kotlin.test library under the hood and runs the test using JUnit.
To get started, first download and install the latest version of IntelliJ IDEA.
Add
dependencies
1. Open a Kotlin project in IntelliJ IDEA. If you don't already have a project, create one.
2. Open the build.gradle(.kts) file and add the following dependency to the Gradle configuration. This dependency will
allow you to work with kotlin.test and JUnit:
Kotlin
dependencies {
// Other dependencies.
testImplementation(kotlin("test"))
}
Groovy
dependencies {
// Other dependencies.
testImplementation 'org.jetbrains.kotlin:kotlin-test'
}
Kotlin
tasks.test {
useJUnitPlatform()
}
Groovy
583
test {
useJUnitPlatform()
}
If you created the project using the Project Wizard, the task will be added automatically.
Add
the
code
to
test
it
1. Open the main.kt file in src/main/kotlin.
The src directory contains Kotlin source files and resources. The main.kt file contains sample code that will print Hello,
World!.
2. Create the Sample class with the sum() function that adds two integers together:
class Sample() {
Create
a
test
1. In IntelliJ IDEA, select Code | Generate | Test... for the Sample class.
Create a test
IntelliJ IDEA creates the SampleTest.kt file in the test directory. This directory contains Kotlin test source files and
584
resources.
You can also manually create a *.kt file for tests in src/test/kotlin.
Check that the sum() function returns the expected value by using the assertEquals() function.
import kotlin.test.Test
import kotlin.test.assertEquals
@Test
fun testSum() {
val expected = 42
assertEquals(expected, testSample.sum(40, 2))
}
}
Run
a
test
1. Run the test using the gutter icon.
You can also run all project tests via the command-line interface using the ./gradlew check command.
585
Check the test result. The test passed successfully
3. Make sure that the test works correctly by changing the expected variable value to 43:
@Test
fun testSum() {
val expected = 43
assertEquals(expected, classForTesting.sum(40, 2))
}
586
What's
next
Once you've finished your first test, you can:
Try to write another test using other kotlin.test functions. For example, you could use the assertNotEquals() function.
Watch these video tutorials on YouTube, which demonstrate how to use Spring Boot with Kotlin and JUnit 5.
Mixing
Java
and
Kotlin
in
one
project
–
tutorial
Kotlin provides the first-class interoperability with Java, and modern IDEs make it even better. In this tutorial, you'll learn
how to use both Kotlin and Java sources in the same project in IntelliJ IDEA. To learn how to start a new Kotlin project in
IntelliJ IDEA, see Getting started with IntellJ IDEA.
Adding
Java
source
code
to
an
existing
Kotlin
project
Adding Java classes to a Kotlin project is pretty straightforward. All you need to do is create a new Java file (Alt + Insert/
Cmd + N) in a directory or package inside your project.
If you already have the Java classes, you can just copy them to the project directories.
You can now consume the Java class from Kotlin or vice versa without any further actions.
587
For example, adding the following Java class:
lets you call it from Kotlin like any other type in Kotlin.
Adding
Kotlin
source
code
to
an
existing
Java
project
Adding a Kotlin file to an existing Java project is pretty much the same.
588
If this is the first time you're adding a Kotlin file to this project, IntelliJ IDEA will prompt you to add the required Kotlin
runtime. For a Java project, configure the Kotlin runtime as a Kotlin Java Module.
The next step is to decide which modules to configure (if the project has more than one module) and whether you want to
add the runtime library to the project or use those provided by the current Kotlin plugin.
You can also open the Kotlin runtime configuration manually from Tools | Kotlin | Configure Kotlin in Project.
Converting
an
existing
Java
file
to
Kotlin
with
J2K
The Kotlin plugin also bundles a Java to Kotlin converter (J2K) that automatically converts Java files to Kotlin. To use J2K
on a file, click Convert Java File to Kotlin File in its context menu or in the Code menu of IntelliJ IDEA.
589
Convert Java to Kotlin
While the converter is not fool-proof, it does a pretty decent job of converting most boilerplate code from Java to Kotlin.
Some manual tweaking however is sometimes required.
Using
Java
records
in
Kotlin
Records are classes in Java for storing immutable data. Records carry a fixed set of values – the records components.
They have a concise syntax in Java and save you from having to write boilerplate code:
// Java
public record Person (String name, int age) {}
The compiler automatically generates a final class inherited from java.lang.Record with the following members:
590
a private final field for each record component
Using
Java
records
from
Kotlin
code
You can use record classes with components that are declared in Java the same way you would use classes with
properties in Kotlin. To access the record component, just use its name like you do for Kotlin properties:
Declare
records
in
Kotlin
Kotlin supports record declaration only for data classes, and the data class must meet the requirements.
Applying @JvmRecord to an existing class is not a binary compatible change. It alters the naming convention of
the class property accessors.
@JvmRecord
data class Person(val name: String, val age: Int)
the record components corresponding to the class properties in the class file
the property accessor methods named according to the Java record naming convention
The data class provides equals(), hashCode(), and toString() method implementations.
Requirements
To declare a data class with the @JvmRecord annotation, it must meet the following requirements:
The class must be in a module that targets JVM 16 bytecode (or 15 if the -Xjvm-enable-preview compiler option is
enabled).
591
The class cannot explicitly inherit any other class (including Any) because all JVM records implicitly inherit
java.lang.Record. However, the class can implement interfaces.
The class cannot declare any properties with backing fields – except those initialized from the corresponding
primary constructor parameters.
The class cannot declare any mutable properties with backing fields.
The primary constructor of the class must be as visible as the class itself.
Enabling
JVM
records
JVM records require the 16 target version or higher of the generated JVM bytecode.
Further
discussion
See this language proposal for JVM records for further technical details and discussion.
Migrating
from
Java
to
Kotlin:
Strings
This guide contains examples of how to perform typical tasks with strings in Java and Kotlin. It will help you migrate from
Java to Kotlin and write your code in the authentic Kotlin way.
Concatenate
strings
In Java, you can do this in the following way:
// Java
String name = "Joe";
System.out.println("Hello, " + name);
System.out.println("Your name is " + name.length() + " characters long");
In Kotlin, use the dollar sign ($) before the variable name to interpolate the value of this variable into your string:
fun main() {
//sampleStart
// Kotlin
val name = "Joe"
println("Hello, $name")
println("Your name is ${name.length} characters long")
//sampleEnd
592
}
You can interpolate the value of a complicated expression by surrounding it with curly braces, like in ${name.length}. See
string templates for more information.
Build
a
string
In Java, you can use the StringBuilder:
// Java
StringBuilder countDown = new StringBuilder();
for (int i = 5; i > 0; i--) {
countDown.append(i);
countDown.append("\n");
}
System.out.println(countDown);
In Kotlin, use buildString() – an inline function that takes logic to construct a string as a lambda argument:
fun main() {
//sampleStart
// Kotlin
val countDown = buildString {
for (i in 5 downTo 1) {
append(i)
appendLine()
}
}
println(countDown)
//sampleEnd
}
Under the hood, the buildString uses the same StringBuilder class as in Java, and you access it via an implicit this inside
the lambda.
Create
a
string
from
collection
items
In Java, you use the Stream API to filter, map, and then collect the items:
// Java
List<Integer> numbers = List.of(1, 2, 3, 4, 5, 6);
String invertedOddNumbers = numbers
.stream()
.filter(it -> it % 2 != 0)
.map(it -> -it)
.map(Object::toString)
.collect(Collectors.joining(", "));
593
System.out.println(invertedOddNumbers);
In Kotlin, use the joinToString() function, which Kotlin defines for every List:
fun main() {
//sampleStart
// Kotlin
val numbers = listOf(1, 2, 3, 4, 5, 6)
val invertedOddNumbers = numbers
.filter { it % 2 != 0 }
.joinToString{ "${-it}" }
println(invertedOddNumbers)
//sampleEnd
}
Set
default
value
if
the
string
is
blank
In Java, you can use the ternary operator:
// Java
public void defaultValueIfStringIsBlank() {
String nameValue = getName();
String name = nameValue.isBlank() ? "John Doe" : nameValue;
System.out.println(name);
}
Kotlin provides the inline function ifBlank() that accepts the default value as an argument:
// Kotlin
import kotlin.random.Random
//sampleStart
fun main() {
val name = getName().ifBlank { "John Doe" }
println(name)
}
Replace
characters
at
the
beginning
and
end
of
a
string
594
In Java, you can use the replaceFirst() and the replaceAll() functions. The replaceAll() function in this case accepts the
regular expression ##$, which defines a string ending with ##:
// Java
String input = "##place##holder##";
String result = input.replaceFirst("##", "").replaceAll("##$", "");
System.out.println(result);
In Kotlin, use the removeSurrounding() function with the string delimiter ##:
fun main() {
//sampleStart
// Kotlin
val input = "##place##holder##"
val result = input.removeSurrounding("##")
println(result)
//sampleEnd
}
Replace
occurrences
In Java, you can use the Pattern and the Matcher classes, for example, to obfuscate some data:
// Java
String input = "login: Pokemon5, password: 1q2w3e4r5t";
Pattern pattern = Pattern.compile("\\w*\\d+\\w*");
Matcher matcher = pattern.matcher(input);
String replacementResult = matcher.replaceAll(it -> "xxx");
System.out.println("Initial input: '" + input + "'");
System.out.println("Anonymized input: '" + replacementResult + "'");
In Kotlin, you use the Regex class that simplifies working with regular expressions. Additionally, use raw strings to simplify
a regex pattern by reducing the count of backslashes:
fun main() {
//sampleStart
// Kotlin
val regex = Regex("""\w*\d+\w*""") // raw string
val input = "login: Pokemon5, password: 1q2w3e4r5t"
val replacementResult = regex.replace(input, replacement = "xxx")
println("Initial input: '$input'")
println("Anonymized input: '$replacementResult'")
//sampleEnd
}
Split
a
string
In Java, to split a string with the period character (.), you need to use shielding (\\). This happens because the split()
595
function of the String class accepts a regular expression as an argument:
// Java
System.out.println(Arrays.toString("Sometimes.text.should.be.split".split("\\.")));
In Kotlin, use the Kotlin function split(), which accepts varargs of delimiters as input parameters:
fun main() {
//sampleStart
// Kotlin
println("Sometimes.text.should.be.split".split("."))
//sampleEnd
}
If you need to split with a regular expression, use the overloaded split() version that accepts the Regex as a parameter.
Take
a
substring
In Java, you can use the substring() function, which accepts an inclusive beginning index of a character to start taking the
substring from. To take a substring after this character, you need to increment the index:
// Java
String input = "What is the answer to the Ultimate Question of Life, the Universe, and
Everything? 42";
String answer = input.substring(input.indexOf("?") + 1);
System.out.println(answer);
In Kotlin, you use the substringAfter() function and don’t need to calculate the index of the character you want to take
a substring after:
fun main() {
//sampleStart
// Kotlin
val input = "What is the answer to the Ultimate Question of Life, the Universe, and
Everything? 42"
val answer = input.substringAfter("?")
println(answer)
//sampleEnd
}
Additionally, you can take a substring after the last occurrence of a character:
fun main() {
//sampleStart
// Kotlin
val input = "To be, or not to be, that is the question."
val question = input.substringAfterLast(",")
println(question)
//sampleEnd
596
}
Use
multiline
strings
Before Java 15, there were several ways to create a multiline string. For example, using the join() function of the String
class:
// Java
String lineSeparator = System.getProperty("line.separator");
String result = String.join(lineSeparator,
"Kotlin",
"Java");
System.out.println(result);
In Java 15, text blocks appeared. There is one thing to keep in mind: if you print a multiline string and the triple-quote is
on the next line, there will be an extra empty line:
// Java
String result = """
Kotlin
Java
""".stripIndent();
System.out.println(result);
The output:
If you put the triple-quote on the same line as the last word, this difference in behavior disappears.
In Kotlin, you can format your line with the quotes on the new line, and there will be no extra empty line in the output. The
left-most character of any line identifies the beginning of the line.
fun main() {
//sampleStart
// Kotlin
val result = """
Kotlin
Java
""".trimIndent()
println(result)
//sampleEnd
597
}
The output:
In Kotlin, you can also use the trimMargin() function to customize the indents:
// Kotlin
fun main() {
val result = """
# Kotlin
# Java
""".trimMargin("#")
println(result)
}
What’s
next?
Look through other Kotlin idioms.
Learn how to convert existing Java code to Kotlin with Java to Kotlin converter.
Get
started
with
Kotlin/JS
for
React
This tutorial demonstrates how to use IntelliJ IDEA for creating a frontend application with Kotlin/JS for React.
Create
an
application
Once you've installed IntelliJ IDEA, it's time to create your first frontend application based on Kotlin/JS with React.
598
2. In the panel on the left, select Kotlin.
3. Enter a project name, select React Application as the project template, and click Next.
By default, your project will use Gradle with Kotlin DSL as the build system.
4. Select the CSS Support and Use styled-components checkboxes and click Finish.
599
Configure a frontend application
Your project opens. By default, you see the file build.gradle.kts, which is the build script created by the Project Wizard
based on your configuration. It includes the kotlin("js") plugin and dependencies required for your frontend application.
Run
the
application
Start the application by clicking Run next to the run configuration at the top of the screen.
Your default web browser opens the URL http://localhost:8080/ with your frontend application.
600
Enter your name in the text box and accept the greetings from your application!
Update
the
application
Show
your
name
backwards
1. Open the file welcome.kt in src/main/kotlin.
The src directory contains Kotlin source files and resources. The file welcome.kt includes sample code that renders the
web page you've just seen.
Use a string template for your reversed name by adding a dollar sign $ and enclosing it in curly braces –
${state.name.reversed()}.
styledDiv {
css {
+WelcomeStyles.textContainer
}
+"Hello ${state.name}!"
+" Your name backwards is ${state.name.reversed()}!"
}
601
4. Go to the browser and enjoy the result.
You will see the changes only if your previous application is still running. If you've stopped your application, run it
again.
Add
an
image
1. Open the file welcome.kt in src/main/kotlin.
2. Add a div container with a child image element img after the styledInput block.
Make sure that you import the react.dom.* and styled.* packages.
div {
img(src = "https://placekitten.com/408/287") {}
}
602
Web page with with an image
Add
a
button
that
changes
text
1. Open the file welcome.kt in src/main/kotlin.
button {
attrs.onClickFunction = {
setState(
WelcomeState(name = "Some name")
)
}
603
+"Change name"
}
What's
next?
Once you have created your first application, you can go to Kotlin hands-on labs and complete long-form tutorials on
Kotlin/JS. They include sample projects, which can serve as nice jumping-off points for your own projects, and contain
useful snippets and patterns.
604
For Kotlin/JS, the following hands-on labs are currently available:
Building Web Applications with React and Kotlin/JS guides you through the process of building a simple web
application using the React framework, shows how a type-safe Kotlin DSL for HTML makes it easy to build reactive
DOM elements, and illustrates how to use third-party React components, and how to obtain information from APIs,
while writing the whole application logic in pure Kotlin/JS.
Building a Full Stack Web App with Kotlin Multiplatform teaches the concepts behind building an application that
targets Kotlin/JVM and Kotlin/JS by building a client-server application that makes use of shared code, serialization,
and other multiplatform paradigms. It also provides a brief introduction to working with Ktor both as a server- and
client-side framework.
Set
up
a
Kotlin/JS
project
Kotlin/JS projects use Gradle as a build system. To let developers easily manage their Kotlin/JS projects, we offer the
kotlin.js Gradle plugin that provides project configuration tools together with helper tasks for automating routines typical
for JavaScript development. For example, the plugin downloads the Yarn package manager for managing npm
dependencies in background and can build a JavaScript bundle from a Kotlin project using webpack. Dependency
management and configuration adjustments can be done to a large part directly from the Gradle build file, with the option
to override automatically generated configurations for full control.
To create a Kotlin/JS project in IntelliJ IDEA, go to File | New | Project. Then select Kotlin and choose a Kotlin/JS target
that suits you best. Don't forget to choose the language for the build script: Groovy or Kotlin.
605
Alternatively, you can apply the org.jetbrains.kotlin.js plugin to a Gradle project manually in the Gradle build file
(build.gradle or build.gradle.kts).
Kotlin
plugins {
kotlin("js") version "'1.5.31"
}
Groovy
plugins {
id 'org.jetbrains.kotlin.js' version '1.5.31'
}
The Kotlin/JS Gradle plugin lets you manage aspects of your project in the kotlin section of the build script.
kotlin {
//...
}
Inside the kotlin section, you can manage the following aspects:
Run configuration
Test configuration
Execution
environments
Kotlin/JS projects can target two different execution environments:
Node.js for running JavaScript code outside of a browser, for example, for server-side scripting.
To define the target execution environment for a Kotlin/JS project, add the js section with browser {} or nodejs {} inside.
606
kotlin {
js {
browser {
}
binaries.executable()
}
}
The instruction binaries.executable() explicitly instructs the Kotlin compiler to emit executable .js files. This is the default
behavior when using the current Kotlin/JS compiler, but the instruction is explicitly required if you are working with the
Kotlin/JS IR compiler, or have set kotlin.js.generate.executable.default=false in your gradle.properties. In those cases,
omitting binaries.executable() will cause the compiler to only generate Kotlin-internal library files, which can be used from
other projects, but not run on their own. (This is typically faster than creating executable files, and can be a possible
optimization when dealing with non-leaf modules of your project.)
The Kotlin/JS plugin automatically configures its tasks for working with the selected environment. This includes
downloading and installing the required environment and dependencies for running and testing the application. This
allows developers to build, run and test simple projects without additional configuration.
Dependencies
Like any other Gradle projects, Kotlin/JS projects support traditional Gradle dependency declarations in the
dependencies section of the build script.
Kotlin
dependencies {
implementation("org.example.myproject", "1.1.0")
}
Groovy
dependencies {
implementation 'org.example.myproject:1.1.0'
}
The Kotlin/JS Gradle plugin also supports dependency declarations for particular source sets in the kotlin section of the
build script.
Kotlin
kotlin {
sourceSets["main"].dependencies {
implementation("org.example.myproject", "1.1.0")
}
607
}
Groovy
kotlin {
sourceSets {
main {
dependencies {
implementation 'org.example.myproject:1.1.0'
}
}
}
}
Please note that not all libraries available for the Kotlin programming language are available when targeting JavaScript:
Only libraries that include artifacts for Kotlin/JS can be used.
If the library you are adding has dependencies on packages from npm, Gradle will automatically resolve these transitive
dependencies as well.
Kotlin
standard
libraries
The dependency on the Kotlin/JS standard library is mandatory for all Kotlin/JS projects, and as such is implicit – no
artifacts need to be added.
If your project contains tests written in Kotlin, you should add a dependency on the kotlin.test library:
Kotlin
dependencies {
testImplementation(kotlin("test-js"))
}
Groovy
dependencies {
testImplementation 'org.jetbrains.kotlin:kotlin-test-js'
}
npm
dependencies
In the JavaScript world, the most common way to manage dependencies is npm. It offers the biggest public repository of
JavaScript modules.
The Kotlin/JS Gradle plugin lets you declare npm dependencies in the Gradle build script, analogous to how you would
declare any other dependencies.
608
To declare an npm dependency, pass its name and version to the npm() function inside a dependency declaration. You
can also specify one or multiple version range based on npm's semver syntax.
Kotlin
dependencies {
implementation(npm("react", "> 14.0.0 <=16.9.0"))
}
Groovy
dependencies {
implementation npm('react', '> 14.0.0 <=16.9.0')
}
To download and install your declared dependencies during build time, the plugin manages its own installation of the Yarn
package manager.
Besides regular dependencies, there are three more types of dependencies that can be used from the Gradle DSL. To
learn more about when each type of dependency can best be used, have a look at the official documentation linked from
npm:
Once an npm dependency is installed, you can use its API in your code as described in Calling JS from Kotlin.
run
task
The Kotlin/JS plugin provides a run task that lets you run pure Kotlin/JS projects without additional configuration.
For running Kotlin/JS projects in the browser, this task is an alias for the browserDevelopmentRun task (which is also
available in Kotlin multiplatform projects). It uses the webpack-dev-server to serve your JavaScript artifacts. If you want to
customize the configuration used by webpack-dev-server, for example adjust the port the server runs on, use the
webpack configuration file.
For running Kotlin/JS projects targeting Node.js, the run task is an alias for the nodeRun task (which is also available in
Kotlin multiplatform projects).
To run a project, execute the standard lifecycle run task, or the alias to which it corresponds:
./gradlew run
609
To automatically trigger a re-build of your application after making changes to the source files, use the Gradle continuous
build feature:
or
./gradlew run -t
Once the build of your project has succeeded, the webpack-dev-server will automatically refresh the browser page.
test
task
The Kotlin/JS Gradle plugin automatically sets up a test infrastructure for projects. For browser projects, it downloads
and installs the Karma test runner with other required dependencies; for Node.js projects, the Mocha test framework is
used.
For running browser tests, the plugin uses Headless Chrome by default. You can also choose other browser to run tests
in, by adding the corresponding entries inside the useKarma section of the build script:
kotlin {
js {
browser {
testTask {
useKarma {
useIe()
useSafari()
useFirefox()
useChrome()
useChromeCanary()
useChromeHeadless()
usePhantomJS()
useOpera()
}
}
}
binaries.executable()
// . . .
}
}
Please note that the Kotlin/JS Gradle plugin does not automatically install these browsers for you, but only uses those
610
that are available in its execution environment. If you are executing Kotlin/JS tests on a continuous integration server, for
example, make sure that the browsers you want to test against are installed.
If you want to skip tests, add the line enabled = false to the testTask.
kotlin {
js {
browser {
testTask {
enabled = false
}
}
binaries.executable()
// . . .
}
}
./gradlew check
Karma
configuration
The Kotlin/JS Gradle plugin automatically generates a Karma configuration file at build time which includes your settings
from the kotlin.js.browser.testTask.useKarma block in your build.gradle(.kts). You can find the file at
build/js/packages/projectName-test/karma.conf.js. To make adjustments to the configuration used by Karma, place your
additional configuration files inside a directory called karma.config.d in the root of your project. All .js configuration files in
this directory will be picked up and are automatically merged into the generated karma.conf.js at build time.
webpack
bundling
For browser targets, the Kotlin/JS plugin uses the widely known webpack module bundler.
webpack
version
The Kotlin/JS plugin uses webpack 5.
If you have projects created with plugin versions earlier than 1.5.0, you can temporarily switch back to webpack 4 used in
these versions by adding the following line to the project's gradle.properties:
kotlin.js.webpack.major.version=4
webpack
task
611
The most common webpack adjustments can be made directly via the kotlin.js.browser.webpackTask configuration block
in the Gradle build file:
outputFileName- the name of the webpacked output file. It will be generated in <projectDir>/build/distibution/ after an
execution of a webpack task. The default value is the project name.
output.libraryTarget- the module system for the webpacked output. Learn more about available module systems for
Kotlin/JS projects. The default value is umd.
webpackTask {
outputFileName = "mycustomfilename.js"
output.libraryTarget = "commonjs2"
}
You can also configure common webpack settings to use in bundling, running, and testing tasks in the
commonWebpackConfig block.
webpack
configuration
file
The Kotlin/JS Gradle plugin automatically generates a standard webpack configuration file at the build time. It is located
in build/js/packages/projectName/webpack.config.js.
If you want to make further adjustments to the webpack configuration, place your additional configuration files inside a
directory called webpack.config.d in the root of your project. When building your project, all .js configuration files will
automatically be merged into the build/js/packages/projectName/webpack.config.js file. To add a new webpack loader,
for example, add the following to a .js file inside the webpack.config.d:
config.module.rules.push({
test: /\.extension$/,
loader: 'loader-name'
});
Building
executables
For building executable JavaScript artifacts through webpack, the Kotlin/JS plugin contains the
browserDevelopmentWebpack and browserProductionWebpack Gradle tasks.
browserDevelopmentWebpack creates development artifacts, which are larger in size, but take little time to create. As
such, use the browserDevelopmentWebpack tasks during active development.
browserProductionWebpack applies dead code elimination to the generated artifacts and minifies the resulting
JavaScript file, which takes more time, but generates executables that are smaller in size. As such, use the
browserProductionWebpack task when preparing your project for production use.
Execute either of these tasks to obtain the respective artifacts for development or production. The generated files will be
available in build/distributions unless specified otherwise.
612
./gradlew browserProductionWebpack
Note that these tasks will only be available if your target is configured to generate executable files (via
binaries.executable()).
CSS
The Kotlin/JS Gradle plugin also provides support for webpack's CSS and style loaders. While all options can be changed
by directly modifying the webpack configuration files that are used to build your project, the most commonly used settings
are available directly from the build.gradle(.kts) file.
To turn on CSS support in your project, set the cssSupport.enabled option in the Gradle build file in the
commonWbpackConfig block. This configuration is also enabled by default when creating a new project using the wizard.
browser {
commonWebpackConfig {
cssSupport.enabled = true
}
binaries.executable()
}
Alternatively, you can add CSS support independently for webpackTask, runTask, and testTask.
webpackTask {
cssSupport.enabled = true
}
runTask {
cssSupport.enabled = true
}
testTask {
useKarma {
// . . .
webpackConfig.cssSupport.enabled = true
}
}
Activating CSS support in your project helps prevent common errors that occur when trying to use style sheets from an
unconfigured project, such as Module parse failed: Unexpected character '@' (14:0).
You can use cssSupport.mode to specify how encountered CSS should be handled. The following values are available:
"extract": styles are extracted into a separate file. They can then be included from an HTML page.
"import": styles are processed as strings. This can be useful if you need access to the CSS from your code (such as val
styles = require("main.css")).
To use different modes for the same project, use cssSupport.rules. Here, you can specify a list of
613
KotlinWebpackCssRules, each of which define a mode, as well as include and exclude patterns.
Yarn
To configure additional Yarn features, place a .yarnrc file in the root of your project. At build time, it gets picked up
automatically.
For example, to use a custom registry for npm packages, add the following line to a file called .yarnrc in the project root:
registry "http://my.registry/api/npm/"
To learn more about .yarnrc, please visit the official Yarn documentation.
Distribution
target
directory
By default, the results of a Kotlin/JS project build reside in the /build/distribution directory within the project root.
To set another location for project distribution files, add the distribution block inside browser in the build script and assign
a value to the directory property. Once you run a project build task, Gradle will save the output bundle in this location
together with project resources.
Kotlin
kotlin {
js {
browser {
distribution {
directory = File("$projectDir/output/")
}
}
binaries.executable()
// . . .
}
}
Groovy
kotlin {
js {
browser {
distribution {
directory = file("$projectDir/output/")
}
}
binaries.executable()
// . . .
}
}
614
Module
name
To adjust the name for the JavaScript module (which is generated in build/js/packages/myModuleName), including the
corresponding .js and .d.ts files, use the moduleName option:
js {
moduleName = "myModuleName"
}
Note that this does not affect the webpacked output in build/distributions.
package.json
customization
The package.json file holds the metadata of a JavaScript package. Popular package registries such as npm require all
published packages to have such a file. They use it to track and manage package publications.
The Kotlin/JS Gradle plugin automatically generates package.json for Kotlin/JS projects during build time. By default, the
file contains essential data: name, version, license, and dependencies, and some other package attributes.
Aside from basic package attributes, package.json can define how a JavaScript project should behave, for example,
identifying scripts that are available to run.
You can add custom entries to the project's package.json via the Gradle DSL. To add custom fields to your package.json,
use the customField function in the compilations packageJson block:
kotlin {
js {
compilations["main"].packageJson {
customField("hello", mapOf("one" to 1, "two" to 2))
}
}
}
When you build the project, this code will add the following block to the package.json file:
Troubleshooting
When building a Kotlin/JS project using Kotlin 1.3.xx, you may encounter a Gradle error if one of your dependencies (or
any transitive dependency) was built using Kotlin 1.4 or higher: Could not determine the dependencies of task
':client:jsTestPackageJson'./ Cannot choose between the following variants. This is a known problem, a workaround is
provided here.
615
Run
Kotlin/JS
Since Kotlin/JS projects are managed with the Kotlin/JS Gradle plugin, you can run your project using the appropriate
tasks. If you're starting with a blank project, ensure that you have some sample code to execute. Create the file
src/main/kotlin/App.kt and fill it with a small "Hello, World"-type code snippet:
fun main() {
console.log("Hello, Kotlin/JS!")
}
Depending on the target platform, some platform-specific extra setup might be required to run your code for the first time.
Run
the
Node.js
target
When targeting Node.js with Kotlin/JS, you can simply execute the run Gradle task. This can be done for example via the
command line, using the Gradle wrapper:
./gradlew run
If you're using IntelliJ IDEA, you can find the run action in the Gradle tool window:
On first start, the kotlin.js Gradle plugin will download all required dependencies to get you up and running. After the build
is completed, the program is executed, and you can see the logging output in the terminal:
616
Executing a Kotlin JS program in IntelliJ IDEA
Run
the
browser
target
When targeting the browser, your project is required to have an HTML page. This page will be served by the development
server while you are working on your application, and should embed your compiled Kotlin/JS file. Create and fill an HTML
file /src/main/resources/index.html:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Hello, Kotlin/JS!</title>
</head>
<body>
</body>
<script src="jsTutorial.js"></script>
</html>
By default, the name of your project's generated artifact (which is created through webpack) that needs to be referenced
is your project name (in this case, jsTutorial). If you've named your project followAlong, make sure to embed
followAlong.js instead of jsTutorial.js
After making these adjustments, start the integrated development server. You can do this from the command line via the
Gradle wrapper:
./gradlew run
When working from IntelliJ IDEA, you can find the run action in the Gradle tool window.
617
After the project has been built, the embedded webpack-dev-server will start running, and will open a (seemingly empty)
browser window pointing to the HTML file you specified previously. To validate that your program is running correctly,
open the developer tools of your browser (for example by right-clicking and choosing the Inspect action). Inside the
developer tools, navigate to the console, where you can see the results of the executed JavaScript code:
With this setup, you can recompile your project after each code change to see your changes. Kotlin/JS also supports a
more convenient way of automatically rebuilding the application while you are developing it. To find out how to set up this
continuous mode, check out the corresponding tutorial.
Development
server
and
continuous
compilation
Instead of manually compiling and executing a Kotlin/JS project every time you want to see the changes you made, you
can use the continuous compilation mode. Instead of using the regular run command, invoke the Gradle wrapper in
continuous mode:
If you are working in IntelliJ IDEA, you can pass the same flag via the run configuration. After running the Gradle run task
for the first time from the IDE, IntelliJ IDEA automatically generates a run configuration for it, which you can edit:
618
Editing run configurations in IntelliJ IDEA
Enabling continuous mode via the Run/Debug Configurations dialog is as easy as adding the --continuous flag to the
arguments for the run configuration:
619
Adding the continuous flag to a run configuration in IntelliJ IDEA
When executing this run configuration, you can note that the Gradle process continues watching for changes to the
program:
620
Gradle waiting for changes
Once a change has been detected, the program will be recompiled automatically. If you still have the page open in the
browser, the development server will trigger an automatic reload of the page, and the changes will become visible. This is
thanks to the integrated webpack-dev-server that is managed by the Kotlin/JS Gradle plugin.
Debug
Kotlin/JS
code
JavaScript source maps provide mappings between the minified code produced by bundlers or minifiers and the actual
source code a developer works with. This way, the source maps enable support for debugging the code during its
execution.
The Kotlin/JS Gradle plugin automatically generates source maps for the project builds, making them available without
any additional configuration.
Debug
in
browser
Most modern browsers provide tools that allow inspecting the page content and debugging the code that executes on it.
Refer to your browser's documentation for more details.
1. Run the project by calling one of the available *Run Gradle tasks, for example, browserDevelopmentRun or
jsBrowserDevelopmentRun in a multiplatform project. Learn more about running Kotlin/JS.
2. Navigate to the page in the browser and launch its developer tools (for example, by right-clicking and selecting the
Inspect action). Learn how to find the developer tools in popular browsers.
3. If your program is logging information to the console, navigate to the Console tab to see this output. Depending on
your browser, these logs can reference the Kotlin source files and lines they come from:
621
Chrome DevTools console
4. Click the file reference on the right to navigate to the corresponding line of code. Alternatively, you can manually
switch to the Sources tab and find the file you need in the file tree. Navigating to the Kotlin file shows you the regular
Kotlin code (as opposed to minified JavaScript):
622
Debugging in Chrome DevTools
You can now start debugging the program. Set a breakpoint by clicking on one of the line numbers. The developer tools
even support setting breakpoints within a statement. As with regular JavaScript code, any set breakpoints will persist
across page reloads. This also makes it possible to debug Kotlin's main() method which is executed when the script is
loaded for the first time.
Debug
in
the
IDE
IntelliJ IDEA Ultimate provides a powerful set of tools for debugging code during development.
623
For debugging Kotlin/JS in IntelliJ IDEA, you'll need a Debug JavaScript debug configuration. To add such a
configuration:
3. Specify the configuration Name and provide the URL on which the project runs (http://localhost:8080 by default).
1. Run the project by calling one of the available *Run Gradle tasks, for example, browserDevelopmentRun or
jsBrowserDevelopmentRun in a multiplatform project. Learn more about running Kotlin/JS.
2. Start the debugging session by running the JavaScript debug configuration you've created previously:
624
JavaScript debug configuration
3. You can see the console output of your program in the Debug window in IntelliJ IDEA. The output items reference the
Kotlin source files and lines they come from:
625
JavaScript debug output in the IDE
4. Click the file reference on the right to navigate to the corresponding line of code.
You can now start debugging the program using the whole set of tools that the IDE offers: breakpoints, stepping,
expression evaluation, and more. Learn more about debugging in IntelliJ IDEA.
Because of the limitations of the current JavaScript debugger in IntelliJ IDEA, you may need to rerun the
JavaScript debug to make the execution stop on breakpoints.
Debug
in
Node.js
If your project targets Node.js, you can debug it in this runtime.
2. Find the resulting .js file for Node.js in the build/js/packages/your-module/kotlin/ directory inside your project's
directory.
626
What's
next?
Now that you know how to start debug sessions with your Kotlin/JS project, learn to make efficient use of the debugging
tools:
If
you
run
into
any
problems
If you face any issues with debugging Kotlin/JS, please report them to our issue tracker, YouTrack
Run
tests
in
Kotlin/JS
The Kotlin/JS Gradle plugin lets you run tests through a variety of test runners that can be specified via the Gradle
configuration. In order to make test annotations and functionality available for the JavaScript target, add the correct
platform artifact for kotlin.test in build.gradle.kts:
dependencies {
// ...
testImplementation(kotlin("test-js"))
}
You can tune how tests are executed in Kotlin/JS by adjusting the settings available in the testTask block in the Gradle
build script. For example, using the Karma test runner together with a headless instance of Chrome and an instance of
Firefox looks like this:
target {
browser {
testTask {
useKarma {
useChromeHeadless()
useFirefox()
}
}
}
}
For a detailed description of the available functionality, check out the Kotlin/JS reference on configuring the test task.
Please note that by default, no browsers are bundled with the plugin. This means that you'll have to ensure they're
available on the target system.
To check that tests are executed properly, add a file src/test/kotlin/AppTest.kt and fill it with this content:
627
import kotlin.test.Test
import kotlin.test.assertEquals
class AppTest {
@Test
fun thingsShouldWork() {
assertEquals(listOf(1,2,3).reversed(), listOf(3,2,1))
}
@Test
fun thingsShouldBreak() {
assertEquals(listOf(1,2,3).reversed(), listOf(1,2,3))
}
}
To run the tests in the browser, execute the browserTest task via IntelliJ IDEA, or use the gutter icons to execute all or
individual tests:
Alternatively, if you want to run the tests via the command line, use the Gradle wrapper:
./gradlew browserTest
After running the tests from IntelliJ IDEA, the Run tool window will show the test results. You can click failed tests to see
their stack trace, and navigate to the corresponding test implementation via a double-click.
628
Test results in IntelliJ IDEA
After each test run, regardless of how you executed the test, you can find a properly formatted test report from Gradle in
build/reports/tests/browserTest/index.html. Open this file in a browser to see another overview of the test results:
629
Gradle test summary
If you are using the set of example tests shown in the snippet above, one test passes, and one test breaks, which gives
the resulting total of 50% successful tests. To get more information about individual test cases, you can navigate via the
provided hyperlinks:
630
Stacktrace of failed test in the Gradle summary
Kotlin/JS
dead
code
elimination
The Kotlin/JS Gradle plugin includes a dead code elimination (DCE) tool. Dead code elimination is often also called tree
shaking. It reduces the size or the resulting JavaScript code by removing unused properties, functions, and classes.
A function is inlined and never gets called directly (which happens always except for a few situations).
A module uses a shared library. Without DCE, parts of the library that you don't use are still included in the resulting
bundle. For example, the Kotlin standard library contains functions for manipulating lists, arrays, char sequences,
adapters for DOM, and so on. All of this functionality would require about 1.3 MB as a JavaScript file. A simple "Hello,
world" application only requires console routines, which is only few kilobytes for the entire file.
The Kotlin/JS Gradle plugin handles DCE automatically when you build a production bundle, for example by using the
browserProductionWebpack task. Development bundling tasks (like browserDevelopmentWebpack) don't include DCE.
631
Exclude
declarations
from
DCE
Sometimes you may need to keep a function or a class in the resulting JavaScript code even if you don't use it in your
module, for example, if you're going to use it in the client JavaScript code.
To keep certain declarations from elimination, add the dceTask block to your Gradle build script and list the declarations
as arguments of the keep function. An argument must be the declaration's fully qualified name with the module name as a
prefix: moduleName.dot.separated.package.name.declarationName
Unless specified otherwise, the names of functions and modules can be mangled in the generated JavaScript
code. To keep such functions from elimination, use the mangled names in the keep arguments as they appear
in the generated JavaScript code.
kotlin {
js {
browser {
dceTask {
keep("myKotlinJSModule.org.example.getName", "myKotlinJSModule.org.example.User"
)
}
binaries.executable()
}
}
}
If you want to keep a whole package or module from elimination, you can use its fully qualified name as it appears in the
generated JavaScript code.
Keeping whole packages or modules from elimination can prevent DCE from removing many unused
declarations. Because of this, it is preferable to select individual declarations which should be excluded from
DCE one by one.
Disable
DCE
To turn off DCE completely, use the devMode option in the dceTask:
kotlin {
js {
browser {
dceTask {
dceOptions.devMode = true
}
}
binaries.executable()
}
}
632
Kotlin/JS
IR
compiler
The Kotlin/JS IR compiler is in Beta. It is almost stable, but migration steps may be required in the future. We'll
do our best to minimize any changes you have to make.
The Kotlin/JS IR compiler backend is the main focus of innovation around Kotlin/JS, and paves the way forward for the
technology.
Rather than directly generating JavaScript code from Kotlin source code, the Kotlin/JS IR compiler backend leverages a
new approach. Kotlin source code is first transformed into a Kotlin intermediate representation (IR), which is subsequently
compiled into JavaScript. For Kotlin/JS, this enables aggressive optimizations, and allows improvements on pain points
that were present in the previous compiler, such as generated code size (through dead code elimination), and JavaScript
and TypeScript ecosystem interoperability, to name some examples.
The IR compiler backend is available starting with Kotlin 1.4.0 through the Kotlin/JS Gradle plugin. To enable it in your
project, pass a compiler type to the js function in your Gradle build script:
kotlin {
js(IR) { // or: LEGACY, BOTH
// ...
}
binaries.executable() // not applicable to BOTH, see details below
}
BOTH compiles your project with the new IR compiler as well as the default compiler backend. Use this mode for
authoring libraries compatible with both backends.
The compiler type can also be set in the gradle.properties file, with the key kotlin.js.compiler=ir. This behaviour is
overwritten by any settings in the build.gradle(.kts), however.
Ignoring
compilation
errors
Ignore compilation errors mode is Experimental. It may be dropped or changed at any time. Opt-in is required
(see the details below), and you should use it only for evaluation purposes. We would appreciate your feedback
on it in YouTrack.
633
Kotlin/JS IR compiler provides a new compilation mode unavailable in the default backend – ignoring compilation
errors. In this mode, you can try out your application even while its code contains errors. For example, when you’re
doing a complex refactoring or working on a part of the system that is completely unrelated to a compilation error in
another part.
With this new compiler mode, the compiler ignores all broken code. Thus, you can run the application and try its parts that
don't use the broken code. If you try to run the code that was broken during compilation, you'll get a runtime exception.
Choose between two tolerance policies for ignoring compilation errors in your code:
SEMANTIC. The compiler will accept code that is syntactically correct but doesn't make sense semantically. For
example, assigning a number to a string variable (type mismatch).
SYNTAX. The compiler will accept any code, even if it contains syntax errors. Regardless of what you write, the
compiler will still try to generate a runnable executable.
As an experimental feature, ignoring compilation errors requires an opt-in. To enable this mode, add the -Xerror-
tolerance-policy={SEMANTIC|SYNTAX} compiler option:
kotlin {
js(IR) {
compilations.all {
compileKotlinTask.kotlinOptions.freeCompilerArgs += listOf("-Xerror-tolerance-
policy=SYNTAX")
}
}
}
Lazy
initialization
of
top-level
properties
Lazy initialization of top-level properties is Experimental. It may be dropped or changed at any time. Opt-in is
required (see the details below), and you should use it only for evaluation purposes. We would appreciate your
feedback on it in YouTrack.
For better application startup performance, the Kotlin/JS IR compiler offers an option to initialize top-level properties
lazily. This way, the application loads without initializing all the top-level properties used in its code. It initializes only the
ones needed at startup; other properties receive their values later when the code that uses them actually runs.
As an experimental feature, lazy initialization of top-level properties requires an opt-in. To use the lazy initialization of top-
level properties, add the -Xir-property-lazy-initialization option when compiling the code with the JS IR compiler:
Kotlin
tasks.withType<Kotlin2JsCompile> {
kotlinOptions {
634
freeCompilerArgs += "-Xir-property-lazy-initialization"
}
}
Groovy
tasks.withType(Kotlin2JsCompile) {
kotlinOptions {
freeCompilerArgs += "-Xir-property-lazy-initialization"
}
}
Preview:
generation
of
TypeScript
declaration
files
(d.ts)
The generation of TypeScript declaration files (d.ts) is Experimental. It may be dropped or changed at any time.
Opt-in is required (see the details below), and you should use it only for evaluation purposes. We would
appreciate your feedback on it in YouTrack.
The Kotlin/JS IR compiler is capable of generating TypeScript definitions from your Kotlin code. These definitions can be
used by JavaScript tools and IDEs when working on hybrid apps to provide autocompletion, support static analyzers, and
make it easier to include Kotlin code in JavaScript and TypeScript projects.
Top-level declarations marked with @JsExport in a project that produces executable files (binaries.executable()) will get a
.d.ts file generated, which contains the TypeScript definitions for the exported Kotlin declarations. These declarations can
be found in build/js/packages/<package_name>/kotlin alongside the corresponding un-webpacked JavaScript code.
Current
limitations
of
the
IR
compiler
A major change with the new IR compiler backend is the absence of binary compatibility with the default backend. A lack
of such compatibility between the two backends for Kotlin/JS means that a library created with the new IR compiler
backend can’t be used from the default backend, and vice versa.
If you want to use the IR compiler backend for your project, you need to update all Kotlin dependencies to versions that
support this new backend. Libraries published by JetBrains for Kotlin 1.4+ targeting Kotlin/JS already contain all artifacts
required for usage with the new IR compiler backend.
If you are a library author looking to provide compatibility with the current compiler backend as well as the new IR
compiler backend, additionally check out the section about authoring libraries for the IR compiler section.
The IR compiler backend also has some discrepancies in comparison to the default backend. When trying out the new
backend, it's good to be mindful of these possible pitfalls.
Currently, the IR backend does not generate source maps for Kotlin code. You can follow the progress on YouTrack.
635
Some libraries that rely on specific characteristics of the default backend, such as kotlin-wrappers, can display some
problems. You can follow the investigation and progress on YouTrack.
The IR backend does not make Kotlin declarations available to JavaScript by default at all. To make Kotlin declarations
visible to JavaScript, they must be annotated with @JsExport.
Migrating
existing
projects
to
the
IR
compiler
Due to significant differences between the two Kotlin/JS compilers, making your Kotlin/JS code work with the IR compiler
may require some adjustments. Learn how to migrate existing Kotlin/JS projects to the IR compiler in the Kotlin/JS IR
compiler migration guide.
Authoring
libraries
for
the
IR
compiler
with
backwards
compatibility
If you're a library maintainer who is looking to provide compatibility with the default backend as well as the new IR
compiler backend, a setting for the compiler selection is available that allows you to create artifacts for both backends,
allowing you to keep compatibility for your existing users while providing support for the next generation of Kotlin
compiler. This so-called both -mode can be turned on using the kotlin.js.compiler=both setting in your gradle.properties
file, or can be set as one of the project-specific options inside your js block inside the build.gradle(.kts) file:
kotlin {
js(BOTH) {
// ...
}
}
When in both mode, the IR compiler backend and default compiler backend are both used when building a library from
your sources (hence the name). This means that both klib files with Kotlin IR as well as jar files for the default compiler will
be generated. When published under the same Maven coordinate, Gradle will automatically choose the right artifact
depending on the use case – js for the old compiler, klib for the new one. This enables you to compile and publish your
library for projects that are using either of the two compiler backends.
Migrating
Kotlin/JS
projects
to
the
IR
compiler
The Kotlin/JS IR compiler is in Beta. It is almost stable, but migration steps may be required in the future. We'll
do our best to minimize any changes you have to make.
We are replacing the current Kotlin/JS compiler with the IR-based compiler in order to unify Kotlin’s behavior on all
platforms and to make it possible to implement new JS-specific optimizations, among other reasons. You can learn more
about the internal differences between the two compilers in the blog post Migrating our Kotlin/JS app to the new IR
636
compiler by Sebastian Aigner.
Due to the significant differences between the compilers, switching your Kotlin/JS project from the old backend to the
new one may require adjusting your code. On this page, we've compiled a list of known migration issues along with
suggested solutions.
Install the Kotlin/JS Inspection pack plugin to get valuable tips on how to fix some of the issues that occur
during migration.
Note that this guide may change over time as we fix issues and find new ones. Please help us keep it complete – report
any issues you encounter when switching to the IR compiler by submitting them to our issue tracker YouTrack or filling
out this form.
Convert
JS-
and
React-related
classes
and
interfaces
to
external
interfaces
Issue: Using Kotlin interfaces and classes (including data classes) that derive from pure JS classes, such as React's State
and Props, can cause a ClassCastException. Such exceptions appear because the compiler attempts to work with
instances of these classes as if they were Kotlin objects, when they actually come from JS.
Solution: convert all classes and interfaces that derive from pure JS classes to external interfaces:
// Replace this
interface AppState : State { }
interface AppProps : Props { }
data class CustomComponentState(var name: String) : State
// With this
external interface AppState : State { }
external interface AppProps : Props { }
external interface CustomComponentState : State {
var name: String
}
In IntelliJ IDEA, you can use these structural search and replace templates to automatically mark interfaces as external:
Convert
properties
of
external
interfaces
to
var
Issue: properties of external interfaces in Kotlin/JS code can't be read-only (val) properties because their values can be
assigned only after the object is created with js() or jsObject() (a helper function from kotlin-wrappers):
637
val myState = js("{}") as CustomComponentState
myState.name = "name"
// Replace this
external interface CustomComponentState : State {
val name: String
}
// With this
external interface CustomComponentState : State {
var name: String
}
Make
boolean
properties
nullable
in
external
interfaces
Issue: JavaScript treats the null or undefined value of a boolean variable as false. So, boolean properties can be used in
expressions without being defined. This is okay in JavaScript, but not in Kotlin.
If you try to use such a property in a function overridden in Kotlin (for example, a React button), you'll get a
ClassCastException:
button {
attrs {
autoFocus = props.visible // ClassCastException here
}
}
// Replace this
external interface ComponentProps: Props {
var visible: Boolean
}
638
// With this
external interface ComponentProps: Props {
var visible: Boolean?
}
Convert
functions
with
receivers
in
external
interfaces
to
regular
functions
Issue: external declarations can't contain functions with receivers, such as extension functions or properties with
corresponding functional types.
Solution: convert such functions and properties to regular functions by adding the receiver object as an argument:
// Replace this
external interface ButtonProps : Props {
var inside: StyledDOMBuilder<BUTTON>.() -> Unit
}
Create
plain
JS
objects
for
interoperability
Issue: properties of a Kotlin object that implements an external interface are not enumerable. This means that they are not
visible for operations that iterate over the object's properties, for example:
console.log(obj)
JSON.stringify(obj)
639
Solution 1: create plain JavaScript objects with js() or jsObject() (a helper function from kotlin-wrappers):
// Replace this
val ktApp = AppPropsImpl("App1") // Kotlin object
// With this
val jsApp = js("{name: 'App1'}") as AppProps // or jsObject {}
// or with this
val jsonApp = kotlin.js.json(Pair("name", "App1")) as AppProps
Replace
toString()
calls
on
function
references
with
.name
Issue: in the IR backend, calling toString() on function references doesn't produce unique values.
Browser
and
DOM
API
The Kotlin/JS standard library lets you access browser-specific functionality using the kotlinx.browser package, which
includes typical top-level objects such as document and window. The standard library provides typesafe wrappers for the
functionality exposed by these objects wherever possible. As a fallback, the dynamic type is used to provide interaction
with functions that do not map well into the Kotlin type system.
Interaction
with
the
DOM
For interaction with the Document Object Model (DOM), you can use the variable document. For example, you can set the
background color of our website through this object:
document.bgColor = "FFAA12"
The document object also provides you a way to retrieve a specific element by ID, name, class name, tag name and so
on. All returned elements are of type Element?. To access their properties, you need to cast them to their appropriate
type. For example, assume that you have an HTML page with an email <input> field:
640
<body>
<input type="text" name="email" id="email"/>
Note that your script is included at the bottom of the body tag. This ensures that the DOM is fully available before the
script is loaded.
With this setup, you can access elements of the DOM. To access the properties of the input field, invoke getElementById
and cast it to HTMLInputElement. You can then safely access its properties, such as value:
Much like you reference this input element, you can access other elements on the page, casting them to the appropriate
types.
To see how to create and structure elements in the DOM in a concise way, check out the Typesafe HTML DSL.
Use
JavaScript
code
from
Kotlin
Kotlin was first designed for easy interoperation with the Java platform: it sees Java classes as Kotlin classes, and Java
sees Kotlin classes as Java classes.
However, JavaScript is a dynamically typed language, which means it does not check types at compile time. You can
freely talk to JavaScript from Kotlin via dynamic types. If you want to use the full power of the Kotlin type system, you can
create external declarations for JavaScript libraries which will be understood by the Kotlin compiler and the surrounding
tooling.
An experimental tool to automatically create Kotlin external declarations for npm dependencies which provide type
definitions (TypeScript / d.ts) called Dukat is also available.
Inline
JavaScript
You can inline some JavaScript code into your Kotlin code using the js() function. For example:
Because the parameter of js is parsed at compile time and translated to JavaScript code "as-is", it is required to be a
string constant. So, the following code is incorrect:
641
return js(getTypeof() + " o") // error reported here
}
fun getTypeof() = "typeof"
Note that invoking js() returns a result of type dynamic, which provides no type safety at the compile time.
external
modifier
To tell Kotlin that a certain declaration is written in pure JavaScript, you should mark it with the external modifier. When
the compiler sees such a declaration, it assumes that the implementation for the corresponding class, function or
property is provided externally (by the developer or via an npm dependency), and therefore does not try to generate any
JavaScript code from the declaration. This is also why external declarations can't have a body. For example:
// etc
}
Note that the external modifier is inherited by nested declarations. This is why in the example Node class, there is no
external modifier before member functions and properties.
The external modifier is only allowed on package-level declarations. You can't declare an external member of a non-
external class.
Declare
(static)
members
of
a
class
In JavaScript you can define members either on a prototype or a class itself:
There is no such syntax in Kotlin. However, in Kotlin we have companion objects. Kotlin treats companion objects of
external classes in a special way: instead of expecting an object, it assumes members of companion objects to be
members of the class itself. MyClass from the example above can be described as follows:
642
fun ownMember()
}
Declare
optional
parameters
If you are writing an external declaration for a JavaScript function which has an optional parameter, use definedExternally.
This delegates the generation of the default values to the JavaScript function itself:
With this external declaration, you can call myFunWithOptionalArgs with one required argument and two optional
arguments, where the default values are calculated by the JavaScript implementation of myFunWithOptionalArgs.
Extend
JavaScript
classes
You can easily extend JavaScript classes as if they were Kotlin classes. Just define an external open class and extend it
by a non- external class. For example:
fun restart() {
window.alert("Restarting")
}
}
When a function of an external base class is overloaded by signature, you can't override it in a derived class.
external
interfaces
JavaScript does not have the concept of interfaces. When a function expects its parameter to support two methods foo
and bar, you would just pass in an object that actually has these methods.
643
You can use interfaces to express this concept in statically typed Kotlin:
fun bar()
}
A typical use case for external interfaces is to describe settings objects. For example:
// etc
}
fun sendQuery() {
JQuery.get(JQueryAjaxSettings().apply {
complete = { (xhr, data) ->
window.alert("Request complete")
}
})
}
as casts to external interfaces always succeed. Casting to external interfaces produces the "Unchecked cast to
external interface" compile time warning. The warning can be suppressed with the
@Suppress("UNCHECKED_CAST_TO_EXTERNAL_INTERFACE") annotation.
IntelliJ IDEA can also automatically generate the @Suppress annotation. Open the intentions menu via the light bulb
icon or Alt-Enter, and click the small arrow next to the "Unchecked cast to external interface" inspection. Here, you can
select the suppression scope, and your IDE will add the annotation to your file accordingly.
644
Casts
In addition to the "unsafe" cast operator as, which throws a ClassCastException in case a cast is not possible, Kotlin/JS
also provides unsafeCast<T>(). When using unsafeCast, no type checking is done at all during runtime. For example,
consider the following two methods:
function usingUnsafeCast(s) {
return s;
}
function usingAsOperator(s) {
var tmp$;
return typeof (tmp$ = s) === 'string' ? tmp$ : throwCCE();
}
Dynamic
type
Being a statically typed language, Kotlin still has to interoperate with untyped or loosely typed environments, such as the
JavaScript ecosystem. To facilitate these use cases, the dynamic type is available in the language:
A value of the dynamic type can be assigned to any variable or passed anywhere as a parameter.
Any value can be assigned to a variable of the dynamic type or passed to a function that takes dynamic as a
parameter.
The most peculiar feature of dynamic is that we are allowed to call any property or function with any parameters on a
dynamic variable:
On the JavaScript platform this code will be compiled "as is": dyn.whatever(1) in Kotlin becomes dyn.whatever(1) in the
645
generated JavaScript code.
When calling functions written in Kotlin on values of dynamic type, keep in mind the name mangling performed by the
Kotlin to JavaScript compiler. You may need to use the @JsName annotation to assign well-defined names to the
functions that you need to call.
A dynamic call always returns dynamic as a result, so you can chain such calls freely:
dyn.foo().bar.baz()
When you pass a lambda to a dynamic call, all of its parameters by default have the type dynamic:
dyn.foo {
x -> x.bar() // x is dynamic
}
Expressions using values of dynamic type are translated to JavaScript "as is", and do not use the Kotlin operator
conventions. The following operators are supported:
binary: +, -, *, /, %, >, < >=, <=, ==, !=, ===, !==, &&, ||
unary
prefix: -, +, !
indexed access:
read: d[a], more than one argument is an error
in, !in and .. operations with values of type dynamic are forbidden.
Use
dependencies
from
npm
In Kotlin/JS projects, all dependencies can be managed through the Gradle plugin. This includes Kotlin/Multiplatform
libraries such as kotlinx.coroutines, kotlinx.serialization, or ktor-client.
For depending on JavaScript packages from npm, the Gradle DSL exposes an npm function that lets you specify
packages you want to import from npm. Let's consider the import of an NPM package called is-sorted.
dependencies {
// ...
implementation(npm("is-sorted", "1.0.5"))
646
}
Because JavaScript modules are usually dynamically typed and Kotlin is a statically typed language, you need to provide
a kind of adapter. In Kotlin, such adapters are called external declarations. For the is-sorted package which offers only
one function, this declaration is small to write. Inside the source folder, create a new file called is-sorted.kt, and fill it with
these contents:
@JsModule("is-sorted")
@JsNonModule
external fun <T> sorted(a: Array<T>): Boolean
Please note that if you're using CommonJS as a target, the @JsModule and @JsNonModule annotations need to be
adjusted accordingly.
This JavaScript function can now be used just like a regular Kotlin function. Because we provided type information in the
header file (as opposed to simply defining parameter and return type to be dynamic), proper compiler support and type-
checking is also available.
console.log("Hello, Kotlin/JS!")
console.log(sorted(arrayOf(1,2,3)))
console.log(sorted(arrayOf(3,1,2)))
Running these three lines either in the browser or Node.js, the output shows that the call to sorted was properly mapped
to the function exported by the is-sorted package:
Hello, Kotlin/JS!
true
false
Because the JavaScript ecosystem has multiple ways of exposing functions in a package (for example through named or
default exports), other npm packages might need a slightly altered structure for their external declarations.
To learn more about how to write declarations, please refer to Calling JavaScript from Kotlin.
Use
Kotlin
code
from
JavaScript
Depending on the selected JavaScript Module system, the Kotlin/JS compiler generates different output. But in general,
the Kotlin compiler generates normal JavaScript classes, functions and properties, which you can freely use from
JavaScript code. There are some subtle things you should remember, though.
Isolating
declarations
in
a
separate
JavaScript
object
in
plain
mode
If you have explicitly set your module kind to be plain, Kotlin creates an object that contains all Kotlin declarations from
the current module. This is done to prevent spoiling the global object. This means that for a module myModule, all
647
declarations are available to JavaScript via the myModule object. For example:
alert(myModule.foo());
This is not applicable when you compile your Kotlin module to JavaScript modules like UMD (which is the default setting
for both browser and nodejs targets), CommonJS or AMD. In this case, your declarations will be exposed in the format
specified by your chosen JavaScript module system. When using UMD or CommonJS, for example, your call site could
look like this:
alert(require('myModule').foo());
Check the article on JavaScript Modules for more information on the topic of JavaScript module systems.
Package
structure
Kotlin exposes its package structure to JavaScript, so unless you define your declarations in the root package, you have
to use fully qualified names in JavaScript. For example:
package my.qualified.packagename
When using UMD or CommonJS, for example, your callsite could look like this:
alert(require('myModule').my.qualified.packagename.foo())
alert(myModule.my.qualified.packagename.foo());
@JsName
annotation
In some cases (for example, to support overloads), the Kotlin compiler mangles the names of generated functions and
attributes in JavaScript code. To control the generated names, you can use the @JsName annotation:
// Module 'kjs'
class Person(val name: String) {
fun hello() {
println("Hello $name!")
}
648
@JsName("helloWithGreeting")
fun hello(greeting: String) {
println("$greeting $name!")
}
}
Now you can use this class from JavaScript in the following way:
If we didn't specify the @JsName annotation, the name of the corresponding function would contain a suffix calculated
from the function signature, for example hello_61zpoe$.
Note that there are some cases in which the Kotlin compiler does not apply mangling:
Any overridden functions in non- external classes inheriting from external classes are not mangled.
The parameter of @JsName is required to be a constant string literal which is a valid identifier. The compiler will report an
error on any attempt to pass non-identifier string to @JsName. The following example produces a compile-time error:
@JsExport
annotation
The @JsExport annotation is currently marked as experimental. Its design may change in future versions.
By applying the @JsExport annotation to a top-level declaration (like a class or function), you make the Kotlin declaration
available from JavaScript. The annotation exports all nested declarations with the name given in Kotlin. It can also be
applied on file-level using @file:JsExport.
To resolve ambiguities in exports (like overloads for functions with the same name), you can use the @JsExport
annotation together with @JsName to specify the names for the generated and exported functions.
The @JsExport annotation is available in the current default compiler backend and the new IR compiler backend. If you
are targeting the IR compiler backend, you must use the @JsExport annotation to make your functions visible from Kotlin
in the first place.
For multiplatform projects, @JsExport is available in common code as well. It only has an effect when compiling for the
JavaScript target, and allows you to also export Kotlin declarations that are not platform specific.
649
Kotlin
types
in
JavaScript
Kotlin numeric types, except for kotlin.Long are mapped to JavaScript Number.
Kotlin can't distinguish between numeric types at run time (except for kotlin.Long), so the following code works:
fun f() {
val x: Int = 23
val y: Any = x
println(y as Float)
}
Kotlin preserves overflow semantics for kotlin.Int, kotlin.Byte, kotlin.Short, kotlin.Char and kotlin.Long.
kotlin.Long is not mapped to any JavaScript object, as there is no 64-bit integer number type in JavaScript. It is
emulated by a Kotlin class.
Kotlin collections (List, Set, Map, and so on) are not mapped to any specific JavaScript type.
Primitive
arrays
Primitive array translation utilizes JavaScript TypedArray:
kotlin.ByteArray, -.ShortArray, -.IntArray, -.FloatArray, and -.DoubleArray are mapped to JavaScript Int8Array,
Int16Array, Int32Array, Float32Array, and Float64Array correspondingly.
JavaScript
modules
You can compile your Kotlin projects to JavaScript modules for various popular module systems. We currently support
650
the following configurations for JavaScript modules:
Unified Module Definitions (UMD), which is compatible with both AMD and CommonJS. UMD modules are also able to
be executed without being imported or when no module system is present. This is the default option for the browser
and nodejs targets.
Asynchronous Module Definitions (AMD), which is in particular used by the RequireJS library.
Plain. Don't compile for any module system. You can access a module by its name in the global scope.
Browser
targets
If you're targeting the browser and want to use a different module system than UMD, you can specify the desired module
type in the webpackTask configuration block. For example, to switch to CommonJS, use:
kotlin {
js {
browser {
webpackTask {
output.libraryTarget = "commonjs2"
}
}
binaries.executable()
}
}
Webpack provides two different "flavors" of CommonJS, commonjs and commonjs2, which affect the way your
declarations are made available. While in most cases, you probably want commonjs2, which adds the module.exports
syntax to the generated library, you can also opt for the "pure" commonjs option, which implements the CommonJS
specification exactly. To learn more about the difference between commonjs and commonjs2, check here.
JavaScript
libraries
and
Node.js
files
If you are creating a library that will be consumed from JavaScript or a Node.js file, and want to use a different module
system, the instructions are slightly different.
Choose
the
target
module
system
To select module kind, set the moduleKind compiler option in the Gradle build script.
Kotlin
tasks.named<KotlinJsCompile>("compileKotlinJs").configure {
kotlinOptions.moduleKind = "commonjs"
651
}
Groovy
compileKotlinJs.kotlinOptions.moduleKind = "commonjs"
This is different from adjusting webpackTask.output.libraryTarget. The library target changes the output
generated by webpack (after your code has already been compiled). kotlinOptions.moduleKind changes the
output generated by the Kotlin compiler.
In the Kotlin Gradle DSL, there is also a shortcut for setting the CommonJS module kind:
kotlin {
js {
useCommonJs()
// . . .
}
}
@JsModule
annotation
To tell Kotlin that an external class, package, function or property is a JavaScript module, you can use @JsModule
annotation. Consider you have the following CommonJS module called "hello":
@JsModule("hello")
external fun sayHello(name: String)
Apply
@JsModule
to
packages
Some JavaScript libraries export packages (namespaces) instead of functions and classes. In terms of JavaScript, it's an
object that has members that are classes, functions and properties. Importing these packages as Kotlin objects often
looks unnatural. The compiler can map imported JavaScript packages to Kotlin packages, using the following notation:
@file:JsModule("extModule")
package ext.jspackage.name
652
external fun foo()
external class C
module.exports = {
foo: { /* some code here */ },
C: { /* some code here */ }
}
Files marked with @file:JsModule annotation can't declare non-external members. The example below produces a
compile-time error:
@file:JsModule("extModule")
package ext.jspackage.name
Import
deeper
package
hierarchies
In the previous example the JavaScript module exports a single package. However, some JavaScript libraries export
multiple packages from within a module. This case is also supported by Kotlin, though you have to declare a new .kt file
for each package you import.
module.exports = {
mylib: {
pkg1: {
foo: function() { /* some code here */ },
bar: function() { /* some code here */ }
},
pkg2: {
baz: function() { /* some code here */ }
}
}
}
To import this module in Kotlin, you have to write two Kotlin source files:
@file:JsModule("extModule")
@file:JsQualifier("mylib.pkg1")
package extlib.pkg1
653
and
@file:JsModule("extModule")
@file:JsQualifier("mylib.pkg2")
package extlib.pkg2
@JsNonModule
annotation
When a declaration is marked as @JsModule, you can't use it from Kotlin code when you don't compile it to a JavaScript
module. Usually, developers distribute their libraries both as JavaScript modules and downloadable .js files that you can
copy to your project's static resources and include via a <script> tag. To tell Kotlin that it's okay to use a @JsModule
declaration from a non-module environment, add the @JsNonModule annotation. For example, consider the following
JavaScript code:
@JsModule("hello")
@JsNonModule
@JsName("topLevelSayHello")
external fun sayHello(name: String)
Module
system
used
by
the
Kotlin
Standard
Library
Kotlin is distributed with the Kotlin/JS standard library as a single file, which is itself compiled as an UMD module, so you
can use it with any module system described above. While for most use cases of Kotlin/JS, it is recommended to use a
Gradle dependency on kotlin-stdlib-js, it is also available on NPM as the kotlin package.
Kotlin/JS
reflection
Kotlin/JS provides a limited support for the Kotlin reflection API. The only supported parts of the API are:
Class
references
654
The ::class syntax returns a reference to the class of an instance, or the class corresponding to the given type. In
Kotlin/JS, the value of a ::class expression is a stripped-down KClass implementation that supports only:
In addition to that, you can use KClass.js to access the JsClass instance corresponding to the class. The JsClass
instance itself is a reference to the constructor function. This can be used to interoperate with JS functions that expect a
reference to a constructor.
KType
and
typeOf()
The typeOf() function is Experimental. It may be dropped or changed at any time. Opt-in is required (see details
below). Use it only for evaluation purposes. We appreciate your feedback on it in YouTrack.
The typeof() function constructs an instance of KType for a given type. To use typeOf() in your code, opt in to the
experimental API of the standard library, for example, add @OptIn(ExperimentalStdlibApi::class) to your code.
The KType API is fully supported in Kotlin/JS except for Java-specific parts.
Example
Here is an example of the reflection usage in Kotlin/JS.
fun main() {
val s = Shape()
val r = Rectangle()
655
Typesafe
HTML
DSL
The kotlinx.html library provides the ability to generate DOM elements using statically typed HTML builders (and besides
JavaScript, it is even available on the JVM target!) To use the library, include the corresponding repository and
dependency to our build.gradle.kts file:
repositories {
// ...
jcenter()
}
dependencies {
implementation(kotlin("stdlib-js"))
implementation("org.jetbrains.kotlinx:kotlinx-html-js:0.7.1")
// ...
}
Once the dependency is included, you can access the different interfaces provided to generate the DOM. To render a
headline, some text, and a link, the following snippet would be sufficient, for example:
import kotlinx.browser.*
import kotlinx.html.*
import kotlinx.html.dom.*
fun main() {
document.body!!.append.div {
h1 {
+"Welcome to Kotlin/JS!"
}
p {
+"Fancy joining this year's "
a("https://kotlinconf.com/") {
+"KotlinConf"
}
+"?"
}
}
}
When running this example in the browser, the DOM will be assembled in a straightforward way. This is easily confirmed
by checking the Elements of the website using the developer tools of our browser:
656
Rendering a website from kotlinx.html
To learn more about the kotlinx.html library, check out the GitHub Wiki, where you can find more information about how to
create elements without adding them to the DOM, binding to events like onClick, and examples on how to apply CSS
classes to your HTML elements, to name just a few.
Generation
of
external
declarations
with
Dukat
Dukat is still experimental. If you encounter any problems, please report them in Dukat's issue tracker.
Dukat is a tool currently in development which allows the automatic conversion of TypeScript declaration files (.d.ts) into
Kotlin external declarations. This aims to makes it more comfortable to use libraries from the JavaScript ecosystem in a
type-safe manner in Kotlin, reducing the need for manually writing external declarations and wrappers for JS libraries.
The Kotlin/JS Gradle plugin provides an integration with Dukat. When enabled, type-safe Kotlin external declarations are
automatically generated for npm dependencies that provide TypeScript definitions. You have two different ways of
selecting if and when Dukat should generate declarations: at build time, and manually via a Gradle task.
Generate
external
declarations
at
build
time
The npm dependency function takes a third parameter after the package name and version: generateExternals. This
allows you to control whether Dukat should generate declarations for a specific dependency:
Kotlin
657
dependencies {
implementation(npm("decamelize", "4.0.0", generateExternals = true))
}
Groovy
dependencies {
implementation(npm('decamelize', '4.0.0', true))
}
If the repository of the dependency you wish to use does not provide TypeScript definitions, you can also use types
provided via the DefinitelyTyped repository. In this case, make sure you add npm dependencies for both your-package
and @types/your-package (with generateExternals = true).
You can use the option kotlin.js.generate.externals in your gradle.properties file to set the generator's behavior for all npm
dependencies simultaneously. As usual, individual explicit settings take precedence over this general option.
Manually
generate
external
declarations
via
Gradle
task
If you want to have full control over the declarations generated by Dukat, want to apply manual adjustments, or if you're
running into trouble with the auto-generated externals, you can also trigger the creation of the declarations for all your
npm dependencies manually via the Gradle task generateExternals (jsGenerateExternals with the multiplatform plugin).
This will generate declarations in a directory titled externals in your project root. Here, you can review the generated code
and copy any parts you would like to use to your source directories.
It is recommended to only provide external declarations manually in your source folder or enabling the generation of
external declarations at build time for any single dependency. Doing both can result in resolution issues.
Hands-on
labs
for
Kotlin/JS
Hands-on labs are long-form tutorials that help you get to know a technology by guiding you through a self-contained
project related to a specific topic.
They include sample projects, which can serve as jumping-off points for your own projects, and contain useful snippets
and patterns.
Building Web Applications with React and Kotlin/JS guides you through the process of building a simple web
application using the React framework, shows how a typesafe Kotlin DSL for HTML makes it convenient to build
reactive DOM elements, and illustrates how to use third-party React components, and how to obtain information from
APIs, while writing the whole application logic in pure Kotlin/JS.
Building a Full Stack Web App with Kotlin Multiplatform teaches the concepts behind building an application that
658
targets Kotlin/JVM and Kotlin/JS by building a client-server application that makes use of common code, serialization,
and other multiplatform paradigms. It also provides a brief introduction into working with Ktor both as a server- and
client-side framework.
We are continuously working on expanding the set of hands-on labs to make it as easy as possible for you to learn more
about Kotlin/JS and adjacent technologies.
Get
started
with
Kotlin/Native
in
IntelliJ
IDEA
This tutorial demonstrates how to use IntelliJ IDEA for creating a Kotlin/Native application.
To get started, install the latest version of IntelliJ IDEA. The tutorial is applicable to both IntelliJ IDEA Community Edition
and the Ultimate Edition.
Create
a
new
Kotlin/Native
project
in
IntelliJ
IDEA
1. In IntelliJ IDEA, select File | New | Project.
3. Enter a project name, select Native Application as the project template, and click Next.
By default, your project will use Gradle with Kotlin DSL as the build system.
659
Kotlin/Native doesn't support Maven and IntelliJ IDEA native builder.
4. Accept the default configuration on the next screen and click Finish.
Your project will open. By default, the wizard creates the necessary main.kt file with code that prints "Hello,
Kotlin/Native!" to the standard output.
The build.gradle.kts file contains the project settings. Read more about these settings in the Kotlin Multiplatform Gradle
DSL reference.
Run
the
application
Start the application by clicking Run next to the run configuration at the top of the screen.
660
Run the application
IntelliJ IDEA opens the Run tab and shows the output:
Application output
Update
the
application
Count
the
letters
in
your
name
1. Open the file main.kt in src/<your_app_name>Main/kotlin.
The src directory contains the Kotlin source files and resources. The file main.kt includes sample code that prints
"Hello, Kotlin/Native!" using the println() function.
2. Add code to read the input. Use the readLine() function to read the input value and assign it to the name variable.
fun main() {
// Read the input value.
println("Hello, enter your name:")
val name = readLine()
}
Check that the provided name is not null with the safe call operator ?..
Use the replace() function to remove the empty spaces in the name.
Use the scope function let to run the function within the object context.
Use a string template to insert your name length into the string by adding a dollar sign $ and enclosing it in curly
braces – ${it.length}. it is the default name of a lambda parameter.
fun main() {
// Read the input value.
println("Hello, enter your name:")
661
val name = readLine()
// Count the letters in the name.
name?.replace(" ", "")?.let {
println("Your name contains ${it.length} letters")
}
}
4. Report a null value using the error() function after the Elvis operator ?:.
fun main() {
// Read the input value.
println("Hello, enter your name:")
val name = readLine()
// Count the letters in the name.
name?.replace(" ", "")?.let {
println("Your name contains ${it.length} letters")
} ?: error("Error while reading input from the terminal: the value can't be null.")
}
IntelliJ IDEA opens the Run tab and shows the output.
Application output
Count
the
unique
letters
in
your
name
1. Open the file main.kt in src/<your_app_name>Main/kotlin.
Convert the input string to a list of characters using the toList() function.
Select only the distinct characters in your name using the distinct() function.
662
fun String.countDistinctCharacters() = lowercase().toList().distinct().count()
3. Use the countDistinctCharacters() function to count the unique letters in your name.
fun main() {
// Read the input value.
println("Hello, enter your name:")
val name = readLine()
// Count the letters in the name.
name?.replace(" ", "")?.let {
println("Your name contains ${it.length} letters")
// Print the number of unique letters.
println("Your name contains ${it.countDistinctCharacters()} unique letters")
} ?: error("Error while reading input from the terminal: the value can't be null.")
}
IntelliJ IDEA opens the Run tab and shows the output.
Application output
What's
next?
Once you have created your first application, you can go to Kotlin hands-on labs and complete long-form tutorials on
Kotlin/Native.
Learn about the concurrency model in Kotlin/Native shows you how to build a command-line application and work with
states in a multi-threaded environment.
Creating an HTTP Client in Kotlin/Native explains how to create a native HTTP client and interoperate with C libraries.
663
Get
started
with
Kotlin/Native
using
Gradle
Gradle is a build system that is very commonly used in the Java, Android, and other ecosystems. It is the default choice
for Kotlin/Native and Multiplatform when it comes to build systems.
While most IDE's including IntelliJ IDEA can generate the corresponding Gradle file, we're going to take a look at how to
create this manually, to have a better understanding of how things work under the covers. If you'd like to use the IDE,
check out Using IntelliJ IDEA.
The Groovy language is the first supported scripting language for Gradle, it leverages the power of dynamic typing and
runtime features of the language. It is also possible to use Kotlin in Gradle scripts. Being a statically-typed language, it
plays better with IDEs when it comes to compilation and error detection.
Either can be used and samples will show the syntax for both languages.
Create
project
files
First, create a project directory. Inside it, create build.gradle or build.gradle.kts Gradle build file with the following
contents:
Kotlin
plugins {
kotlin("multiplatform") version "1.5.31"
}
repositories {
mavenCentral()
}
kotlin {
macosX64("native") { // on macOS
// linuxX64("native") // on Linux
// mingwX64("native") // on Windows
binaries {
executable()
}
}
}
tasks.withType<Wrapper> {
gradleVersion = "6.7.1"
distributionType = Wrapper.DistributionType.BIN
}
664
Groovy
plugins {
id 'org.jetbrains.kotlin.multiplatform' version '1.5.31'
}
repositories {
mavenCentral()
}
kotlin {
macosX64('native') { // on macOS
// linuxX64('native') // on Linux
// mingwX64('native') // on Windows
binaries {
executable()
}
}
}
wrapper {
gradleVersion = '6.7.1'
distributionType = 'BIN'
}
Depending on the target platform, different functions, such as macosX64, mingwX64, linuxX64, iosX64, are used for
creating the Kotlin target. The function name is the platform for which you are compiling your code. These functions
optionally take the target name as a parameter, which is "native" in our case. The specified target name is used to
generate the source paths and task names in the project.
By convention, all sources are located in the src/<target name>[Main|Test]/kotlin folders, where main is for the source
code and test is for tests. <target name> corresponds to the target platform (in this case native), as specified in the build
file.
Create a folder src/nativeMain/kotlin and inside it place the file hello.kt with the following contents:
fun main() {
println("Hello Kotlin/Native!")
}
Build
the
project
From the root project folder, execute the build by running
gradle nativeBinaries
This should create a folder build/bin/native with two subfolders debugExecutable and releaseExecutable with the
corresponding binary. By default, the binary's name is the same as the project folder.
665
Open
the
project
in
an
IDE
Any IDE that supports Gradle should allow for opening the project in the IDE. In the case of IntelliJ IDEA, just open the
project folder, and it will automatically detect it as Kotlin/Native project.
What's
next?
Learn how to write Gradle build scripts for real-life Kotlin/Native projects.
Get
started
with
Kotlin/Native
using
the
command-line
compiler
Obtain
the
compiler
The Kotlin/Native compiler is available for macOS, Linux, and Windows. It is available as a command line tool and ships
as part of the standard Kotlin distribution and can be downloaded from GitHub Releases. It supports different targets
including iOS (arm32, arm64, simulator x86_64), Windows (mingw32 and x86_64), Linux (x86_64, arm64, MIPS), macOS
(x86_64), Raspberry PI, SMT32, WASM. See the full list of targets here. While cross-platform compilation is possible,
which means using one platform to compile for a different one, in this Kotlin case we'll be targeting the same platform
we're compiling on.
While the output of the compiler does not have any dependencies or virtual machine requirements, the compiler itself
requires Java 1.8 or higher runtime.
Install the compiler by unpacking its archive to a directory of your choice and adding the path to its /bin directory to the
PATH environment variable.
Write
"Hello
Kotlin/Native"
program
The application will print "Hello Kotlin/Native" on the standard output. In a working directory of choice, create a file named
hello.kt and enter the following contents:
fun main() {
println("Hello Kotlin/Native!")
}
Compile
the
code
from
the
console
To compile the application use the downloaded compiler to execute the following command:
666
kotlinc-native hello.kt -o hello
The value of -o option specifies the name of the output file, so this call should generate a hello.kexe (Linux and macOS) or
hello.exe (Windows) binary file. For the full list of available compiler options, see the compiler options reference.
While compilation from the console seems to be easy and clear, it does not scale well for larger projects with hundreds of
files and libraries. For real-world projects, it is recommended to use a build system and IDE.
Concurrency
in
Kotlin/Native
Kotlin/Native runtime doesn't encourage a classical thread-oriented concurrency model with mutually exclusive code
blocks and conditional variables, as this model is known to be error-prone and unreliable. Instead, we suggest a
collection of alternative approaches, allowing you to use hardware concurrency and implement blocking IO. Those
approaches are as follows, and they will be elaborated on in further sections:
Workers
Instead of threads Kotlin/Native runtime offers the concept of workers: concurrently executed control flow streams with
an associated request queue. Workers are very similar to the actors in the Actor Model. A worker can exchange Kotlin
objects with another worker, so that at any moment each mutable object is owned by a single worker, but ownership can
be transferred. See section Object transfer and freezing.
Once a worker is started with the Worker.start function call, it can be addressed with its own unique integer worker id.
Other workers, or non-worker concurrency primitives, such as OS threads, can send a message to the worker with the
execute call.
667
future.consume {
// Here we see result returned from routine above. Note that future object or
// id could be transferred to another worker, so we don't have to consume future
// in same execution context it was obtained.
result -> println("result is $result")
}
The call to execute uses a function passed as its second parameter to produce an object subgraph (i.e. set of mutually
referring objects) which is then passed as a whole to that worker, it is then no longer available to the thread that initiated
the request. This property is checked if the first parameter is TransferMode.SAFE by graph traversal and is just assumed
to be true, if it is TransferMode.UNSAFE. The last parameter to execute is a special Kotlin lambda, which is not allowed to
capture any state, and is actually invoked in the target worker's context. Once processed, the result is transferred to
whatever consumes it in the future, and it is attached to the object graph of that worker/thread.
If an object is transferred in UNSAFE mode and is still accessible from multiple concurrent executors, program will likely
crash unexpectedly, so consider that last resort in optimizing, not a general purpose mechanism.
For a more complete example please refer to the workers example in the Kotlin/Native repository.
Object
transfer
and
freezing
An important invariant that Kotlin/Native runtime maintains is that the object is either owned by a single thread/worker, or
it is immutable (shared XOR mutable). This ensures that the same data has a single mutator, and so there is no need for
locking to exist. To achieve such an invariant, we use the concept of not externally referred object subgraphs. This is a
subgraph which has no external references from outside of the subgraph, which could be checked algorithmically with
O(N) complexity (in ARC systems), where N is the number of elements in such a subgraph. Such subgraphs are usually
produced as a result of a lambda expression, for example some builder, and may not contain objects, referred to
externally.
Freezing is a runtime operation making a given object subgraph immutable, by modifying the object header so that future
mutation attempts throw an InvalidMutabilityException. It is deep, so if an object has a pointer to other objects - transitive
closure of such objects will be frozen. Freezing is a one way transformation, frozen objects cannot be unfrozen. Frozen
objects have a nice property that due to their immutability, they can be freely shared between multiple workers/threads
without breaking the "mutable XOR shared" invariant.
If an object is frozen it can be checked with an extension property isFrozen, and if it is, object sharing is allowed.
Currently, Kotlin/Native runtime only freezes the enum objects after creation, although additional autofreezing of certain
provably immutable objects could be implemented in the future.
Object
subgraph
detachment
An object subgraph without external references can be disconnected using DetachedObjectGraph<T> to a
COpaquePointer value, which could be stored in void* data, so the disconnected object subgraphs can be stored in a C
data structure, and later attached back with DetachedObjectGraph<T>.attach() in an arbitrary thread or a worker.
Combining it with raw memory sharing it allows side channel object transfer between concurrent threads, if the worker
mechanisms are insufficient for a particular task. Note, that object detachment may require explicit leaving function
668
holding object references and then performing cyclic garbage collection. For example, code like:
will not work as expected and will throw runtime exception, as there are uncollected cycles in the detached graph, while:
will work properly, as holding references will be released, and then cyclic garbage affecting reference counter is collected.
Raw
shared
memory
Considering the strong ties between Kotlin/Native and C via interoperability, in conjunction with the other mechanisms
mentioned above it is possible to build popular data structures, like concurrent hashmap or shared cache with
Kotlin/Native. It is possible to rely upon shared C data, and store in it references to detached object subgraphs. Consider
the following .def file:
package = global
---
typedef struct {
int version;
void* kotlinObject;
} SharedData;
SharedData sharedData;
After running the cinterop tool it can share Kotlin data in a versionized global structure, and interact with it from Kotlin
transparently via autogenerated Kotlin like this:
669
So in combination with the top-level variable declared above, it can allow looking at the same memory from different
threads and building traditional concurrent structures with platform-specific synchronization primitives.
Global
variables
and
singletons
Frequently, global variables are a source of unintended concurrency issues, so Kotlin/Native implements the following
mechanisms to prevent the unintended sharing of state via global objects:
global variables, unless specially marked, can be only accessed from the main thread (that is, the thread Kotlin/Native
runtime was first initialized), if other thread access such a global, IncorrectDereferenceException is thrown
for global variables marked with the @kotlin.native.ThreadLocal annotation each threads keeps thread-local copy, so
changes are not visible between threads
for global variables marked with the @kotlin.native.SharedImmutable annotation value is shared, but frozen before
publishing, so each threads sees the same value
singleton objects unless marked with @kotlin.native.ThreadLocal are frozen and shared, lazy values allowed, unless
cyclic frozen structures were attempted to be created
Combined, these mechanisms allow natural race-free programming with code reuse across platforms in MPP projects.
Atomic
primitives
and
references
Kotlin/Native standard library provides primitives for safe working with concurrently mutable data, namely AtomicInt,
AtomicLong, AtomicNativePtr, AtomicReference and FreezableAtomicReference in the package kotlin.native.concurrent.
Atomic primitives allows concurrency-safe update operations, such as increment, decrement and compare-and-swap,
along with value setters and getters. Atomic primitives are considered always frozen by the runtime, and while their fields
can be updated with the regular field.value += 1, it is not concurrency safe. Value must be be changed using dedicated
operations, so it is possible to perform concurrent-safe global counters and similar data structures.
Some algorithms require shared mutable references across the multiple workers, for example global mutable
configuration could be implemented as an immutable instance of properties list atomically replaced with the new version
on configuration update as the whole in a single transaction. This way no inconsistent configuration could be seen, and at
the same time configuration could be updated as needed. To achieve such functionality Kotlin/Native runtime provides
two related classes: kotlin.native.concurrent.AtomicReference and kotlin.native.concurrent.FreezableAtomicReference.
Atomic reference holds reference to a frozen or immutable object, and its value could be updated by set or compare-and-
swap operation. Thus, dedicated set of objects could be used to create mutable shared object graphs (of immutable
objects). Cycles in the shared memory could be created using atomic references. Kotlin/Native runtime doesn't support
garbage collecting cyclic data when reference cycle goes through AtomicReference or frozen FreezableAtomicReference.
So to avoid memory leaks atomic references that are potentially parts of shared cyclic data should be zeroed out once no
longer needed.
If atomic reference value is attempted to be set to non-frozen value runtime exception is thrown.
670
Freezable atomic reference is similar to the regular atomic reference, but until frozen behaves like regular box for a
reference. After freezing it behaves like an atomic reference, and can only hold a reference to a frozen object.
Immutability
in
Kotlin/Native
Kotlin/Native implements strict mutability checks, ensuring the important invariant that the object is either immutable or
accessible from the single thread at that moment in time (mutable XOR global).
Immutability is a runtime property in Kotlin/Native, and can be applied to an arbitrary object subgraph using the
kotlin.native.concurrent.freeze function. It makes all the objects reachable from the given one immutable, such a transition
is a one-way operation (i.e., objects cannot be unfrozen later). Some naturally immutable objects such as kotlin.String,
kotlin.Int, and other primitive types, along with AtomicInt and AtomicReference are frozen by default. If a mutating
operation is applied to a frozen object, an InvalidMutabilityException is thrown.
To achieve mutable XOR global invariant, all globally visible state (currently, object singletons and enums) are
automatically frozen. If object freezing is not desired, a kotlin.native.ThreadLocal annotation can be used, which will make
the object state thread local, and so, mutable (but the changed state is not visible to other threads).
Top level/global variables of non-primitive types are by default accessible in the main thread (i.e., the thread which
initialized Kotlin/Native runtime first) only. Access from another thread will lead to an IncorrectDereferenceException
being thrown. To make such variables accessible in other threads, you can use either the @ThreadLocal annotation, and
mark the value thread local or @SharedImmutable, which will make the value frozen and accessible from other threads.
Class AtomicReference can be used to publish the changed frozen state to other threads, and so build patterns like
shared caches.
Kotlin/Native
libraries
Kotlin
compiler
specifics
To produce a library with the Kotlin/Native compiler use the -produce library or -p library flag. For example:
This command will produce a bar.klib with the compiled contents of foo.kt.
To link to a library use the -library <name> or -l <name> flag. For example:
671
cinterop
tool
specifics
The cinterop tool produces .klib wrappers for native libraries as its main output. For example, using the simple libgit2.def
native library definition file provided in your Kotlin/Native distribution
klib
utility
The klib library management utility allows you to inspect and install the libraries.
remove – remove the library from the default repository use
All of the above commands accept an additional -repository <directory> argument for specifying a repository different to
the default one.
Several
examples
First let's create a library. Place the tiny library source code into kotlinizer.kt:
672
package kotlinizer
val String.kotlinized
get() = "Kotlin $this"
$ ls kotlinizer.klib
kotlinizer.klib
$ rm kotlinizer.klib
import kotlinizer.*
Now compile the program linking with the library you have just created:
$ ./kohello.kexe
Hello, Kotlin world!
Have fun!
673
Advanced
topics
Library
search
sequence
When given a -library foo flag, the compiler searches the foo library in the following order:
Libraries installed in the default repository (For now the default is ~/.konan, however it could be changed by setting
KONAN_DATA_DIR environment variable).
Library
format
Kotlin/Native libraries are zip files containing a predefined directory structure, with the following layout:
- foo/
- $component_name/
- ir/
- Serialized Kotlin IR.
- targets/
- $platform/
- kotlin/
- Kotlin compiled to LLVM bitcode.
- native/
- Bitcode files of additional native objects.
- $another_platform/
- There can be several platform specific kotlin and native pairs.
- linkdata/
- A set of ProtoBuf files with serialized linkage metadata.
- resources/
- General resources such as images. (Not used yet).
- manifest - A file in the java property format describing the library.
Platform
libraries
To provide access to user's native operating system services, Kotlin/Native distribution includes a set of prebuilt libraries
specific to each target. We call them Platform Libraries.
POSIX
bindings
674
For all Unix- or Windows-based targets (including Android and iOS targets) we provide the posix platform lib. It contains
bindings to platform's implementation of the POSIX standard.
import platform.posix.*
Note that the content of platform.posix is NOT identical on different platforms, in the same way as different POSIX
implementations are a little different.
Popular
native
libraries
There are many more platform libraries available for host and cross-compilation targets. Kotlin/Native distribution
provides access to OpenGL, zlib and other popular native libraries on applicable platforms.
Availability
by
default
The packages from platform libraries are available by default. No special link flags need to be specified to use them.
Kotlin/Native compiler automatically detects which of the platform libraries have been accessed and automatically links
the needed libraries.
On the other hand, the platform libs in the distribution are merely just wrappers and bindings to the native libraries. That
means the native libraries themselves (.so, .a, .dylib, .dll etc) should be installed on the machine.
Examples
The Kotlin/Native repository provides a wide spectrum of examples demonstrating the use of platform libraries. See
samples for details.
Kotlin/Native
as
a
dynamic
library
–
tutorial
Learn how you can use the Kotlin/Native code from existing native applications or libraries. For this, you need to compile
the Kotlin code into a dynamic library, .so, .dylib, and .dll.
Kotlin/Native also has tight integration with Apple technologies. The Kotlin/Native as an Apple Framework tutorial explains
how to compile Kotlin code into a framework for Swift and Objective-C.
675
In this tutorial, you will:
Compile and run the example on Linux and Mac and Windows
Create
a
Kotlin
library
Kotlin/Native compiler can produce a dynamic library out of the Kotlin code. A dynamic library often comes with a header
file, a .h file, which you will use to call the compiled code from C.
The best way to understand these techniques is to try them out. First, create a first tiny Kotlin library and use it from a C
program.
package example
object Object {
val field = "A"
}
class Clazz {
fun memberFunction(p: Int): ULong = 42UL
}
While it is possible to use the command line, either directly or by combining it with a script file (such as .sh or .bat file),
this approach doesn't scale well for big projects that have hundreds of files and libraries. It is then better to use the
Kotlin/Native compiler with a build system, as it helps to download and cache the Kotlin/Native compiler binaries and
libraries with transitive dependencies and run the compiler and tests. Kotlin/Native can use the Gradle build system
through the kotlin-multiplatform plugin.
We covered the basics of setting up an IDE compatible project with Gradle in the A Basic Kotlin/Native Application
tutorial. Please check it out if you are looking for detailed first steps and instructions on how to start a new Kotlin/Native
project and open it in IntelliJ IDEA. In this tutorial, we'll look at the advanced C interop related usages of Kotlin/Native and
multiplatform builds with Gradle.
First, create a project folder. All the paths in this tutorial will be relative to this folder. Sometimes the missing directories
676
will have to be created before any new files can be added.
Kotlin
plugins {
kotlin("multiplatform") version "1.5.31"
}
repositories {
mavenCentral()
}
kotlin {
linuxX64("native") { // on Linux
// macosX64("native") { // on x86_64 macOS
// macosArm64("native") { // on Apple Silicon macOS
// mingwX64("native") { // on Windows
binaries {
sharedLib {
baseName = "native" // on Linux and macOS
// baseName = "libnative" // on Windows
}
}
}
}
tasks.wrapper {
gradleVersion = "6.7.1"
distributionType = Wrapper.DistributionType.ALL
}
Groovy
plugins {
id 'org.jetbrains.kotlin.multiplatform' version '1.5.31'
}
repositories {
mavenCentral()
}
kotlin {
linuxX64("native") { // on Linux
// macosX64("native") { // on x86_64 macOS
// macosArm64("native") { // on Apple Silicon macOS
// mingwX64("native") { // on Windows
binaries {
sharedLib {
baseName = "native" // on Linux and macOS
// baseName = "libnative" // on Windows
}
}
}
}
677
wrapper {
gradleVersion = "6.7.1"
distributionType = "ALL"
}
Move the sources file into the src/nativeMain/kotlin folder under the project. This is the default path, for where sources are
located, when the kotlin-multiplatform plugin is used. Use the following block to instruct and configure the project to
generate a dynamic or shared library:
binaries {
sharedLib {
baseName = "native" // on Linux and macOS
// baseName = "libnative" // on Windows
}
}
The libnative is used as the library name, the generated header file name prefix. It is also prefixes all declarations in the
header file.
Now you can open the project in IntelliJ IDEA and to see how to fix the example project. While doing this, we'll examine
how C functions are mapped into Kotlin/Native declarations.
Run the linkNative Gradle task to build the library in the IDE or by calling the following console command:
./gradlew linkNative
The build generates the following files under the build/bin/native/debugShared folder, depending on the host OS:
The same rules are used by the Kotlin/Native compiler to generate the .h file for all platforms.
Let's check out the C API of our Kotlin library.`
Generated
headers
file
In the libnative_api.h, you'll find the following code. Let's discuss the code in parts to make it easier to understand.
The very first part contains the standard C/C++ header and footer:
678
#ifndef KONAN_DEMO_H
#define KONAN_DEMO_H
#ifdef __cplusplus
extern "C" {
#endif
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif /* KONAN_DEMO_H */
After the rituals in the libnative_api.h, there is a block with the common type definitions:
#ifdef __cplusplus
typedef bool libnative_KBoolean;
#else
typedef _Bool libnative_KBoolean;
#endif
typedef unsigned short libnative_KChar;
typedef signed char libnative_KByte;
typedef short libnative_KShort;
typedef int libnative_KInt;
typedef long long libnative_KLong;
typedef unsigned char libnative_KUByte;
typedef unsigned short libnative_KUShort;
typedef unsigned int libnative_KUInt;
typedef unsigned long long libnative_KULong;
typedef float libnative_KFloat;
typedef double libnative_KDouble;
typedef void* libnative_KNativePtr;
Kotlin uses the libnative_ prefix for all declarations in the created libnative_api.h file. Let's present the mapping of the
types in a more readable way:
libnative_KShort short
libnative_KInt int
679
Kotlin Define C Type
libnative_KFloat float
libnative_KDouble double
libnative_KNativePtr void*
The definitions part shows how Kotlin primitive types map into C primitive types. The reverse mapping is described in the
Mapping primitive data types from C tutorial.
The next part of the libnative_api.h file contains definitions of the types that are used in the library:
struct libnative_KType;
typedef struct libnative_KType libnative_KType;
typedef struct {
libnative_KNativePtr pinned;
} libnative_kref_example_Object;
typedef struct {
libnative_KNativePtr pinned;
} libnative_kref_example_Clazz;
The typedef struct { .. } TYPE_NAME syntax is used in C language to declare a structure. This thread on Stackoverflow
provides more explanations of that pattern.
As you can see from these definitions, the Kotlin object Object is mapped into libnative_kref_example_Object, and Clazz
is mapped into libnative_kref_example_Clazz. Both structs contain nothing but the pinned field with a pointer, the field
type libnative_KNativePtr is defined as void* above.
There is no namespaces support in C, so the Kotlin/Native compiler generates long names to avoid any possible clashes
with other symbols in the existing native project.
A significant part of the definitions goes in the libnative_api.h file. It includes the definition of our Kotlin/Native library
world:
typedef struct {
/* Service functions. */
void (*DisposeStablePointer)(libnative_KNativePtr ptr);
680
void (*DisposeString)(const char* string);
libnative_KBoolean (*IsInstance)(libnative_KNativePtr ref, const libnative_KType* type);
/* User functions. */
struct {
struct {
struct {
void (*forIntegers)(libnative_KByte b, libnative_KShort s, libnative_KUInt i,
libnative_KLong l);
void (*forFloats)(libnative_KFloat f, libnative_KDouble d);
const char* (*strings)(const char* str);
const char* (*get_globalString)();
struct {
libnative_KType* (*_type)(void);
libnative_kref_example_Object (*_instance)();
const char* (*get_field)(libnative_kref_example_Object thiz);
} Object;
struct {
libnative_KType* (*_type)(void);
libnative_kref_example_Clazz (*Clazz)();
libnative_KULong (*memberFunction)(libnative_kref_example_Clazz thiz, libnative_KInt
p);
} Clazz;
} example;
} root;
} kotlin;
} libnative_ExportedSymbols;
The code uses anonymous structure declarations. The code struct { .. } foo declares a field in the outer struct of that
anonymous structure type, the type with no name.
C does not support objects either. People use function pointers to mimic object semantics. A function pointer is declared
as follows RETURN_TYPE (* FIELD_NAME)(PARAMETERS). It is tricky to read, but we should be able to see function
pointer fields in the structures above.
Runtime
functions
The code reads as follows. You have the libnative_ExportedSymbols structure, which defines all the functions that
Kotlin/Native and our library provides us. It uses nested anonymous structures heavily to mimic packages. The libnative_
prefix comes from the library name.
These functions deal with Kotlin/Native objects. Call the DisposeStablePointer to release a Kotlin object and
DisposeString to release a Kotlin String, which has the char* type in C. It is possible to use the IsInstance function to
check if a Kotlin type or a libnative_KNativePtr is an instance of another type. The actual set of operations generated
depends on the actual usages.
Kotlin/Native has garbage collection, but it does not help us deal with Kotlin objects from the C language. Kotlin/Native
681
has interop with Objective-C and Swift and integrates with their reference counters. The Objective-C Interop
documentation article contains more details on it. Also, there is the tutorial Kotlin/Native as an Apple Framework.
Your
library
functions
Let's take a look at the kotlin.root.example field, it mimics the package structure of our Kotlin code with a kotlin.root.
prefix.
There is a kotlin.root.example.Clazz field that represents the Clazz from Kotlin. The Clazz#memberFunction is accessible
with the memberFunction field. The only difference is that the memberFunction accepts a this reference as the first
parameter. The C language does not support objects, and this is the reason to pass a this pointer explicitly.
There is a constructor in the Clazz field (aka kotlin.root.example.Clazz.Clazz), which is the constructor function to create
an instance of the Clazz.
Kotlin object Object is accessible as kotlin.root.example.Object. There is the _instance function to get the only instance of
the object.
Properties are translated into functions. The get_ and set_ prefix is used to name the getter and the setter functions
respectively. For example, the read-only property globalString from Kotlin is turned into a get_globalString function in C.
Global functions forInts, forFloats, or strings are turned into the functions pointers in the kotlin.root.example anonymous
struct.
Entry
point
You can see how the API is created. To start with, you need to initialize the libnative_ExportedSymbols structure. Let's
take a look at the latest part of the libnative_api.h for this:
The function libnative_symbols allows you to open the way from the native code to the Kotlin/Native library. This is the
entry point you'll use. The library name is used as a prefix for the function name.
Kotlin/Native object references do not support multi-threaded access. Hosting the returned
libnative_ExportedSymbols* pointer per thread might be necessary.
Use
generated
headers
from
C
The usage from C is straightforward and uncomplicated. Create a main.c file with the following code:
#include "libnative_api.h"
#include "stdio.h"
682
//obtain reference for calling Kotlin/Native functions
libnative_ExportedSymbols* lib = libnative_symbols();
lib->kotlin.root.example.forIntegers(1, 2, 3, 4);
lib->kotlin.root.example.forFloats(1.0f, 2.0);
return 0;
}
Compile
and
run
the
example
on
Linux
and
macOS
On macOS 10.13 with Xcode, compile the C code and link it with the dynamic library with the following command:
The compiler generates an executable called a.out. Run it to see in action the Kotlin code being executed from C library.
On Linux, you'll need to include . into the LD_LIBRARY_PATH to let the application know to load the libnative.so library
from the current folder.
Compile
and
run
the
example
on
Windows
To start with, you'll need a Microsoft Visual C++ compiler installed that supports a x64_64 target. The easiest way to do
this is to have a version of Microsoft Visual Studio installed on a Windows machine.
In this example, you'll be using the x64 Native Tools Command Prompt <VERSION> console. You'll see the shortcut to
open the console in the start menu. It comes with a Microsoft Visual Studio package.
On Windows, Dynamic libraries are included either via a generated static library wrapper or with manual code, which
deals with the LoadLibrary or similar Win32API functions. Follow the first option and generate the static wrapper library for
the libnative.dll as described below.
Call lib.exe from the toolchain to generate the static library wrapper libnative.lib that automates the DLL usage from the
683
code:
Now you are ready to compile our main.c into an executable. Include the generated libnative.lib into the build command
and start:
The command produces the main.exe file, which you can run.
Next
steps
Dynamic libraries are the main way to use Kotlin code from existing programs. You can use them to share your code with
many platforms or languages, including JVM, Python, iOS, Android, and others.
Kotlin/Native also has tight integration with Objective-C and Swift. It is covered in the Kotlin/Native as an Apple
Framework tutorial.
Interoperability
with
C
Kotlin/Native follows the general tradition of Kotlin to provide excellent existing platform software interoperability. In the
case of a native platform, the most important interoperability target is a C library. So Kotlin/Native comes with a cinterop
tool, which can be used to quickly generate everything needed to interact with an external library.
The following workflow is expected when interacting with the native library:
The interoperability tool analyses C headers and produces a "natural" mapping of the types, functions, and constants into
the Kotlin world. The generated stubs can be imported into an IDE for the purpose of code completion and navigation.
Platform
libraries
Note that in many cases there's no need to use custom interoperability library creation mechanisms described below, as
for APIs available on the platform standardized bindings called platform libraries could be used. For example, POSIX on
Linux/macOS platforms, Win32 on Windows platform, or Apple frameworks on macOS/iOS are available this way.
684
Simple
example
Install libgit2 and prepare stubs for the git library:
cd samples/gitchurn
../../dist/bin/cinterop -def src/nativeInterop/cinterop/libgit2.def \
-compiler-option -I/usr/local/include -o libgit2
../../dist/bin/kotlinc src/gitChurnMain/kotlin \
-library libgit2 -o GitChurn
./GitChurn.kexe ../..
Create
bindings
for
a
new
library
To create bindings for a new library, start from creating a .def file. Structurally it's a simple property file, which looks like
this:
headers = png.h
headerFilter = png.h
package = png
Then run the cinterop tool with something like this (note that for host libraries that are not included in the sysroot search
paths, headers may be needed):
This command will produce a png.klib compiled library and png-build/kotlin directory containing Kotlin source code for
the library.
If the behavior for a certain platform needs to be modified, you can use a format like compilerOpts.osx or
compilerOpts.linux to provide platform-specific values to the options.
Note that the generated bindings are generally platform-specific, so if you are developing for multiple targets, the bindings
need to be regenerated.
After the generation of bindings, they can be used by the IDE as a proxy view of the native library.
For a typical Unix library with a config script, the compilerOpts will likely contain the output of a config script with the --
cflags flag (maybe without exact paths).
685
The output of a config script with --libs will be passed as a -linkedArgs kotlinc flag value (quoted) when compiling.
Select
library
headers
When library headers are imported to a C program with the #include directive, all of the headers included by these
headers are also included in the program. So all header dependencies are included in generated stubs as well.
This behavior is correct but it can be very inconvenient for some libraries. So it is possible to specify in the .def file which
of the included headers are to be imported. The separate declarations from other headers can also be imported in case of
direct dependencies.
The globs are applied to the header paths relative to the appropriate include path elements, e.g. time.h or curl/curl.h. So if
the library is usually included with #include <SomeLibrary/Header.h>, then it would probably be correct to filter headers
with
headerFilter = SomeLibrary/**
When both excludeDependentModules and headerFilter are used, they are applied as an intersection.
C
compiler
and
linker
options
Options passed to the C compiler (used to analyze headers, such as preprocessor definitions) and the linker (used to link
final executables) can be passed in the definition file as compilerOpts and linkerOpts respectively. For example:
compilerOpts = -DFOO=bar
linkerOpts = -lpng
686
Target-specific options only applicable to the certain target can be specified as well:
compilerOpts = -DBAR=bar
compilerOpts.linux_x64 = -DFOO=foo1
compilerOpts.mac_x64 = -DFOO=foo2
With such a configuration, C headers will be analyzed with -DBAR=bar -DFOO=foo1 on Linux and with -DBAR=bar -
DFOO=foo2 on macOS . Note that any definition file option can have both common and the platform-specific part.
Add
custom
declarations
Sometimes it is required to add custom C declarations to the library before generating bindings (e.g., for macros). Instead
of creating an additional header file with these declarations, you can include them directly to the end of the .def file, after
a separating line, containing only the separator sequence ---:
headers = errno.h
---
Note that this part of the .def file is treated as part of the header file, so functions with the body should be declared as
static. The declarations are parsed after including the files from the headers list.
Include
a
static
library
in
your
klib
Sometimes it is more convenient to ship a static library with your product, rather than assume it is available within the
user's environment. To include a static library into .klib use staticLibrary and libraryPaths clauses. For example:
headers = foo.h
staticLibraries = libfoo.a
libraryPaths = /opt/local/lib /usr/local/opt/curl/lib
When given the above snippet the cinterop tool will search libfoo.a in /opt/local/lib and /usr/local/opt/curl/lib, and if it is
found include the library binary into klib.
When using such klib in your program, the library is linked automatically.
Bindings
Basic
interop
types
All the supported C types have corresponding representations in Kotlin:
687
Signed, unsigned integral, and floating point types are mapped to their Kotlin counterpart with the same width.
Enums can be mapped to either Kotlin enum or integral values, depending on heuristics and the definition file hints.
Structs and unions are mapped to types having fields available via the dot notation, i.e. someStructInstance.field1.
Also, any C type has the Kotlin type representing the lvalue of this type, i.e., the value located in memory rather than a
simple immutable self-contained value. Think C++ references, as a similar concept. For structs (and typedef s to structs)
this representation is the main one and has the same name as the struct itself, for Kotlin enums it is named ${type}Var, for
CPointer<T> it is CPointerVar<T>, and for most other types it is ${type}Var.
For types that have both representations, the one with a "lvalue" has a mutable .value property for accessing the value.
Pointer types
The type argument T of CPointer<T> must be one of the "lvalue" types described above, e.g., the C type struct S* is
mapped to CPointer<S>, int8_t* is mapped to CPointer<int_8tVar>, and char** is mapped to
CPointer<CPointerVar<ByteVar>>.
C null pointer is represented as Kotlin's null, and the pointer type CPointer<T> is not nullable, but the CPointer<T>? is.
The values of this type support all the Kotlin operations related to handling null, e.g. ?:, ?., !! etc.:
Since the arrays are also mapped to CPointer<T>, it supports the [] operator for accessing values by index:
The .pointed property for CPointer<T> returns the lvalue of type T, pointed by this pointer. The reverse operation is .ptr: it
takes the lvalue and returns the pointer to it.
void* is mapped to COpaquePointer – the special pointer type which is the supertype for any other pointer type. So if
the C function takes void*, then the Kotlin binding accepts any CPointer.
or
688
As is with C, these reinterpret casts are unsafe and can potentially lead to subtle memory problems in the application.
Also there are unsafe casts between CPointer<T>? and Long available, provided by the .toLong() and .toCPointer<T>()
extension methods:
Note that if the type of the result is known from the context, the type argument can be omitted as usual due to the type
inference.
Memory
allocation
The native memory can be allocated using the NativePlacement interface, e.g.
or
The most "natural" placement is in the object nativeHeap. It corresponds to allocating native memory with malloc and
provides an additional .free() operation to free allocated memory:
However, the lifetime of allocated memory is often bound to the lexical scope. It is possible to define such scope with
memScoped { ... }. Inside the braces, the temporary placement is available as an implicit receiver, so it is possible to
allocate native memory with alloc and allocArray, and the allocated memory will be automatically freed after leaving the
scope.
For example, the C function returning values through pointer parameters can be used like
Pass
pointers
to
bindings
Although C pointers are mapped to the CPointer<T> type, the C function pointer-typed parameters are mapped to
CValuesRef<T>. When passing CPointer<T> as the value of such a parameter, it is passed to the C function as is.
689
However, the sequence of values can be passed instead of a pointer. In this case the sequence is passed "by value", i.e.,
the C function receives the pointer to the temporary copy of that sequence, which is valid only until the function returns.
The CValuesRef<T> representation of pointer parameters is designed to support C array literals without explicit native
memory allocation. To construct the immutable self-contained sequence of C values, the following methods are provided:
Array<CPointer<T>?>.toCValues(), List<CPointer<T>?>.toCValues()
For example:
C:
Kotlin:
foo(cValuesOf(1, 2, 3), 3)
Strings
Unlike other pointers, the parameters of type const char* are represented as a Kotlin String. So it is possible to pass any
Kotlin string to a binding expecting a C string.
There are also some tools available to convert between Kotlin and C strings manually:
To skip automatic conversion and ensure raw pointers are used in the bindings, a noStringConversion statement in the
.def file could be used, i.e.
This way any value of type CPointer<ByteVar> can be passed as an argument of const char* type. If a Kotlin string should
be passed, code like this could be used:
690
memScoped {
LoadCursorA(null, "cursor.bmp".cstr.ptr) // for ASCII version
LoadCursorW(null, "cursor.bmp".wcstr.ptr) // for Unicode version
}
Scope-local
pointers
It is possible to create a scope-stable pointer of C representation of CValues<T> instance using the CValues<T>.ptr
extension property, available under memScoped { ... }. It allows using the APIs which require C pointers with a lifetime
bound to a certain MemScope. For example:
memScoped {
items = arrayOfNulls<CPointer<ITEM>?>(6)
arrayOf("one", "two").forEachIndexed { index, value -> items[index] = value.cstr.ptr }
menu = new_menu("Menu".cstr.ptr, items.toCValues().ptr)
...
}
In this example, all values passed to the C API new_menu() have a lifetime of the innermost memScope it belongs to.
Once the control flow leaves the memScoped scope the C pointers become invalid.
Pass
and
receive
structs
by
value
When a C function takes or returns a struct / union T by value, the corresponding argument type or return type is
represented as CValue<T>.
CValue<T> is an opaque type, so the structure fields cannot be accessed with the appropriate Kotlin properties. It should
be possible, if an API uses structures as handles, but if field access is required, there are the following conversion
methods available:
fun T.readValue(): CValue<T>. Converts (the lvalue) T to a CValue<T>. So to construct the CValue<T>, T can be
allocated, filled, and then converted to CValue<T>.
CValue<T>.useContents(block: T.() -> R): R. Temporarily places the CValue<T> to memory, and then runs the passed
lambda with this placed value T as receiver. So to read a single field, the following code can be used:
Callbacks
To convert a Kotlin function to a pointer to a C function, staticCFunction(::kotlinFunction) can be used. It is also able to
provide the lambda instead of a function reference. The function or lambda must not capture any values.
691
can't be directly passed to C. So they require wrapping before configuring the callback and then unwrapping in the
callback itself, to safely swim from Kotlin to Kotlin through the C world. Such wrapping is possible with StableRef class.
The created StableRef should eventually be manually disposed using the .dispose() method to prevent memory leaks:
stableRef.dispose()
Macros
Every C macro that expands to a constant is represented as a Kotlin property. Other macros are not supported. However,
they can be exposed manually by wrapping them with supported declarations. E.g. function-like macro FOO can be
exposed as function foo by adding the custom declaration to the library:
headers = library/base.h
---
Definition
file
hints
The .def file supports several options for adjusting the generated bindings.
excludedFunctions property value specifies a space-separated list of the names of functions that should be ignored.
This may be required because a function declared in the C header is not generally guaranteed to be really callable, and
it is often hard or impossible to figure this out automatically. This option can also be used to workaround a bug in the
interop itself.
692
strictEnums and nonStrictEnums properties values are space-separated lists of the enums that should be generated as
a Kotlin enum or as integral values correspondingly. If the enum is not included into any of these lists, then it is
generated according to the heuristics.
noStringConversion property value is space-separated lists of the functions whose const char* parameters shall not be
autoconverted as Kotlin string
Portability
Sometimes the C libraries have function parameters or struct fields of a platform-dependent type, e.g. long or size_t.
Kotlin itself doesn't provide neither implicit integer casts nor C-style integer casts (e.g. (size_t) intValue), so to make
writing portable code in such cases easier, the convert method is provided:
where each of type1 and type2 must be an integral type, either signed or unsigned.
.convert<${type}> has the same semantics as one of the .toByte, .toShort, .toInt, .toLong, .toUByte, .toUShort, .toUInt or
.toULong methods, depending on type.
Also, the type parameter can be inferred automatically and so may be omitted in some cases.
Object
pinning
Kotlin objects could be pinned, i.e. their position in memory is guaranteed to be stable until unpinned, and pointers to
such objects inner data could be passed to the C functions. For example
if (length <= 0) {
break
}
// Now `buffer` has raw data obtained from the `recv()` call.
}
}
}
Here we use service function usePinned, which pins an object, executes block and unpins it on normal and exception
paths.
693
Mapping
primitive
data
types
from
C
–
tutorial
In this tutorial, you will learn what C data types are visible in Kotlin/Native and vice versa. You will:
Types
in
C
language
What types are there in the C language? Let's take the C data types article from Wikipedia as a basis. There are following
types in the C programming language:
basic types char, int, float, double with modifiers signed, unsigned, short, long
pointers
function pointers
There are also the following type qualifiers in the C language: const, volatile, restruct, atomic.
The best way to see what C data types are visible in Kotlin is to try it.
Example
C
library
Create a lib.h file to see how C functions are mapped into Kotlin:
#ifndef LIB2_H_INCLUDED
#define LIB2_H_INCLUDED
#endif
694
The file is missing the extern "C" block, which is not needed for this example, but may be necessary if you use C++ and
overloaded functions. The C++ compatibility thread on Stackoverflow contains more details on this.
For every set of .h files, you will be using the cinterop tool from Kotlin/Native to generate a Kotlin/Native library, or .klib.
The generated library will bridge calls from Kotlin/Native to C. It includes respective Kotlin declarations for the definitions
form the .h files. It is only necessary to have a .h file to run the cinterop tool. And you do not need to create a lib.c file,
unless you want to compile and run the example. More details on this are covered in the C interop page. It is enough for
the tutorial to create the lib.def file with the following content:
headers = lib.h
You may include all declarations directly into the .def file after a --- separator. It can be helpful to include macros or other
C defines into the code generated by the cinterop tool. Method bodies are compiled and fully included into the binary too.
Use that feature to have a runnable example without a need for a C compiler. To implement that, you need to add
implementations to the C functions from the lib.h file, and place these functions into a .def file. You will have the following
interop.def result:
---
The interop.def file is enough to compile and run the application or open it in an IDE. Now it is time to create project files,
open the project in IntelliJ IDEA and run it.
Inspect
generated
Kotlin
APIs
for
a
C
library
While it is possible to use the command line, either directly or by combining it with a script file (such as .sh or .bat file),
this approach doesn't scale well for big projects that have hundreds of files and libraries. It is then better to use the
Kotlin/Native compiler with a build system, as it helps to download and cache the Kotlin/Native compiler binaries and
libraries with transitive dependencies and run the compiler and tests. Kotlin/Native can use the Gradle build system
through the kotlin-multiplatform plugin.
We covered the basics of setting up an IDE compatible project with Gradle in the A Basic Kotlin/Native Application
tutorial. Please check it out if you are looking for detailed first steps and instructions on how to start a new Kotlin/Native
project and open it in IntelliJ IDEA. In this tutorial, we'll look at the advanced C interop related usages of Kotlin/Native and
multiplatform builds with Gradle.
First, create a project folder. All the paths in this tutorial will be relative to this folder. Sometimes the missing directories
will have to be created before any new files can be added.
Kotlin
695
plugins {
kotlin("multiplatform") version "1.5.31"
}
repositories {
mavenCentral()
}
kotlin {
linuxX64("native") { // on Linux
// macosX64("native") { // on x86_64 macOS
// macosArm64("native") { // on Apple Silicon macOS
// mingwX64("native") { // on Windows
val main by compilations.getting
val interop by main.cinterops.creating
binaries {
executable()
}
}
}
tasks.wrapper {
gradleVersion = "6.7.1"
distributionType = Wrapper.DistributionType.BIN
}
Groovy
plugins {
id 'org.jetbrains.kotlin.multiplatform' version '1.5.31'
}
repositories {
mavenCentral()
}
kotlin {
linuxX64('native') { // on Linux
// macosX64("native") { // on x86_64 macOS
// macosArm64("native") { // on Apple Silicon macOS
// mingwX64('native') { // on Windows
compilations.main.cinterops {
interop
}
binaries {
executable()
}
}
}
wrapper {
gradleVersion = '6.7.1'
distributionType = 'BIN'
}
696
The project file configures the C interop as an additional step of the build. Let's move the interop.def file to the
src/nativeInterop/cinterop directory. Gradle recommends using conventions instead of configurations, for example, the
source files are expected to be in the src/nativeMain/kotlin folder. By default, all the symbols from C are imported to the
interop package, you may want to import the whole package in our .kt files. Check out the kotlin-multiplatform plugin
documentation to learn about all the different ways you could configure it.
Create a src/nativeMain/kotlin/hello.kt stub file with the following content to see how C primitive type declarations are
visible from Kotlin:
import interop.*
fun main() {
println("Hello Kotlin/Native!")
ints(/* fix me*/)
uints(/* fix me*/)
doubles(/* fix me*/)
}
Now you are ready to open the project in IntelliJ IDEA and to see how to fix the example project. While doing that, see
how C primitive types are mapped into Kotlin/Native.
Primitive
types
in
kotlin
With the help of IntelliJ IDEA's Go to | Declaration or compiler errors, you see the following generated API for the C
functions:
C types are mapped in the way we would expect, note that char type is mapped to kotlin.Byte as it is usually an 8-bit
signed value.
C Kotlin
char kotlin.Byte
short kotlin.Short
int kotlin.Int
697
C Kotlin
float kotlin.Float
double kotlin.Double
Fix
the
code
You've seen all definitions and it is the time to fix the code. Run the runDebugExecutableNative Gradle task in IDE or use
the following command to run the code:
./gradlew runDebugExecutableNative
The final code in the hello.kt file may look like that:
import interop.*
fun main() {
println("Hello Kotlin/Native!")
ints(1, 2, 3, 4)
uints(5, 6, 7, 8)
doubles(9.0f, 10.0)
}
Next
steps
Continue to explore more complicated C language types and their representation in Kotlin/Native in the next tutorials:
698
Mapping
struct
and
union
types
from
C
–
tutorial
This is the second post in the series. The very first tutorial of the series is Mapping primitive data types from C. There are
also the Mapping function pointers from C and Mapping Strings from C tutorials.
Mapping
struct
and
union
C
types
The best way to understand the mapping between Kotlin and C is to try a tiny example. We will declare a struct and a
union in the C language, to see how they are mapped into Kotlin.
Kotlin/Native comes with the cinterop tool, the tool generates bindings between the C language and Kotlin. It uses a .def
file to specify a C library to import. More details are discussed in the Interop with C Libraries tutorial.
In the previous tutorial, you've created a lib.h file. This time, include those declarations directly into the interop.def file,
after the --- separator line:
---
typedef struct {
int a;
double b;
} MyStruct;
void struct_by_value(MyStruct s) {}
void struct_by_pointer(MyStruct* s) {}
typedef union {
int a;
MyStruct b;
float c;
} MyUnion;
void union_by_value(MyUnion u) {}
void union_by_pointer(MyUnion* u) {}
The interop.def file is enough to compile and run the application or open it in an IDE. Now it is time to create project files,
open the project in IntelliJ IDEA and run it.
Inspect
Generated
Kotlin
APIs
for
a
C
library
699
While it is possible to use the command line, either directly or by combining it with a script file (such as .sh or .bat file),
this approach doesn't scale well for big projects that have hundreds of files and libraries. It is then better to use the
Kotlin/Native compiler with a build system, as it helps to download and cache the Kotlin/Native compiler binaries and
libraries with transitive dependencies and run the compiler and tests. Kotlin/Native can use the Gradle build system
through the kotlin-multiplatform plugin.
We covered the basics of setting up an IDE compatible project with Gradle in the A Basic Kotlin/Native Application
tutorial. Please check it out if you are looking for detailed first steps and instructions on how to start a new Kotlin/Native
project and open it in IntelliJ IDEA. In this tutorial, we'll look at the advanced C interop related usages of Kotlin/Native and
multiplatform builds with Gradle.
First, create a project folder. All the paths in this tutorial will be relative to this folder. Sometimes the missing directories
will have to be created before any new files can be added.
Kotlin
plugins {
kotlin("multiplatform") version "1.5.31"
}
repositories {
mavenCentral()
}
kotlin {
linuxX64("native") { // on Linux
// macosX64("native") { // on x86_64 macOS
// macosArm64("native") { // on Apple Silicon macOS
// mingwX64("native") { // on Windows
val main by compilations.getting
val interop by main.cinterops.creating
binaries {
executable()
}
}
}
tasks.wrapper {
gradleVersion = "6.7.1"
distributionType = Wrapper.DistributionType.BIN
}
Groovy
plugins {
id 'org.jetbrains.kotlin.multiplatform' version '1.5.31'
}
repositories {
mavenCentral()
700
}
kotlin {
linuxX64('native') { // on Linux
// macosX64("native") { // on x86_64 macOS
// macosArm64("native") { // on Apple Silicon macOS
// mingwX64('native') { // on Windows
compilations.main.cinterops {
interop
}
binaries {
executable()
}
}
}
wrapper {
gradleVersion = '6.7.1'
distributionType = 'BIN'
}
The project file configures the C interop as an additional step of the build. Let's move the interop.def file to the
src/nativeInterop/cinterop directory. Gradle recommends using conventions instead of configurations, for example, the
source files are expected to be in the src/nativeMain/kotlin folder. By default, all the symbols from C are imported to the
interop package, you may want to import the whole package in our .kt files. Check out the kotlin-multiplatform plugin
documentation to learn about all the different ways you could configure it.
Create a src/nativeMain/kotlin/hello.kt stub file with the following content to see how C declarations are visible from
Kotlin:
import interop.*
fun main() {
println("Hello Kotlin/Native!")
struct_by_value(/* fix me*/)
struct_by_pointer(/* fix me*/)
union_by_value(/* fix me*/)
union_by_pointer(/* fix me*/)
}
Now you are ready to open the project in IntelliJ IDEA and to see how to fix the example project. While doing that, see
how C primitive types are mapped into Kotlin/Native.
Primitive
types
in
Kotlin
With the help of IntelliJ IDEA's Go to | Declaration or compiler errors, you see the following generated API for the C
functions, struct, and union:
701
fun struct_by_pointer(s: CValuesRef<MyStruct>?)
You see that cinterop generated wrapper types for our struct and union types. For MyStruct and MyUnion type
declarations in C, there are the Kotlin classes MyStruct and MyUnion generated respectively. The wrappers inherit from
the CStructVar base class and declare all fields as Kotlin properties. It uses CValue<T> to represent a by-value structure
parameter and CValuesRef<T>? to represent passing a pointer to a structure or a union.
Technically, there is no difference between struct and union types on the Kotlin side. Note that a, b, and c properties of
MyUnion class in Kotlin use the same memory location to read/write their value just like union does in C language.
Use
struct
and
union
types
from
Kotlin
It is easy to use the generated wrapper classes for C struct and union types from Kotlin. Thanks to the generated
properties, it feels natural to use them in Kotlin code. The only question, so far, is how to create a new instance on those
classes. As you see from the declarations of MyStruct and MyUnion, their constructors require a NativePtr. Of course, you
are not willing to deal with pointers manually. Instead, you can use Kotlin API to have those objects instantiated for us.
Let's take a look at the generated functions that take our MyStruct and MyUnion as parameters. You see that by-value
parameters are represented as kotlinx.cinterop.CValue<T>. And for typed pointer parameters you see
kotlinx.cinterop.CValuesRef<T>. Kotlin provides us with an API to deal with both types easily, let's try it and see.
Create
a
CValue
CValue<T> type is used to pass by-value parameters to a C function call. Use cValue function to create CValue<T> object
instance. The function requires a lambda function with a receiver to initialize the underlying C type in-place. The function
is declared as follows:
Now it is time to see how to use cValue and pass by-value parameters:
702
fun callValue() {
union_by_value(cUnion)
}
Create
struct
and
union
as
CValuesRef
CValuesRef<T> type is used in Kotlin to pass a typed pointer parameter of a C function. First, you need an instance of
MyStruct and MyUnion classes. Create them directly in the native memory. Use the
NativePlacement represents native memory with functions similar to malloc and free. There are several implementations
of NativePlacement. The global one is called with kotlinx.cinterop.nativeHeap and don't forget to call the
nativeHeap.free(..) function to free the memory after use.
function. It creates a short-lived memory allocation scope, and all allocations will be cleaned up automatically at the end
of the block.
Your code to call functions with pointers will look like this:
fun callRef() {
memScoped {
val cStruct = alloc<MyStruct>()
cStruct.a = 42
cStruct.b = 3.14
struct_by_pointer(cStruct.ptr)
union_by_pointer(cUnion.ptr)
703
}
}
Note that this code uses the extension property ptr which comes from a memScoped lambda receiver type, to turn
MyStruct and MyUnion instances into native pointers.
The MyStruct and MyUnion classes have the pointer to the native memory underneath. The memory will be released when
a memScoped function ends, which is equal to the end of its block. Make sure that a pointer is not used outside of the
memScoped call. You may use Arena() or nativeHeap for pointers that should be available longer, or are cached inside a C
library.
Conversion
between
CValue
and
CValuesRef
Of course, there are use cases when you need to pass a struct as a value to one call, and then, to pass the same struct as
a reference to another call. This is possible in Kotlin/Native too. A NativePlacement will be needed here.
fun callMix_ref() {
val cStruct = cValue<MyStruct> {
a = 42
b = 3.14
}
memScoped {
struct_by_pointer(cStruct.ptr)
}
}
This code uses the extension property ptr which comes from memScoped lambda receiver type to turn MyStruct and
MyUnion instances into native pointers. Those pointers are only valid inside the memScoped block.
For the opposite conversion, to turn a pointer into a by-value variable, we call the readValue() extension function:
fun callMix_value() {
memScoped {
val cStruct = alloc<MyStruct>()
cStruct.a = 42
cStruct.b = 3.14
struct_by_value(cStruct.readValue())
}
}
Run
the
code
Now when you have learned how to use C declarations in your code, you are ready to try it out on a real example. Let's fix
the code and see how it runs by calling the runDebugExecutableNative Gradle task in the IDE or by using the following
704
console command:
./gradlew runDebugExecutableNative
The final code in the hello.kt file may look like this:
import interop.*
import kotlinx.cinterop.alloc
import kotlinx.cinterop.cValue
import kotlinx.cinterop.memScoped
import kotlinx.cinterop.ptr
import kotlinx.cinterop.readValue
fun main() {
println("Hello Kotlin/Native!")
memScoped {
union_by_value(cUnion)
union_by_pointer(cUnion.ptr)
}
memScoped {
val cStruct = alloc<MyStruct> {
a = 42
b = 3.14
}
struct_by_value(cStruct.readValue())
struct_by_pointer(cStruct.ptr)
}
}
Next
steps
Continue exploring the C language types and their representation in Kotlin/Native in the related tutorials:
Mapping
function
pointers
from
C
–
tutorial
705
This is the third post in the series. The very first tutorial is Mapping primitive data types from C. There are also Mapping
struct and union types from C and Mapping strings from C tutorials.
Mapping
function
pointer
types
from
C
The best way to understand the mapping between Kotlin and C is to try a tiny example. Declare a function that accepts a
function pointer as a parameter and another function that returns a function pointer.
Kotlin/Native comes with the cinterop tool; the tool generates bindings between the C language and Kotlin. It uses a .def
file to specify a C library to import. More details on this are in Interop with C Libraries.
The quickest way to try out C API mapping is to have all C declarations in the interop.def file, without creating any .h of .c
files at all. Then place the C declarations in a .def file after the special --- separator line:
---
int myFun(int i) {
return i+1;
}
void accept_fun(MyFun f) {
f(42);
}
MyFun supply_fun() {
return myFun;
}
The interop.def file is enough to compile and run the application or open it in an IDE. Now it is time to create project files,
open the project in IntelliJ IDEA and run it.
Inspect
generated
Kotlin
APIs
for
a
C
library
While it is possible to use the command line, either directly or by combining it with a script file (such as .sh or .bat file),
this approach doesn't scale well for big projects that have hundreds of files and libraries. It is then better to use the
Kotlin/Native compiler with a build system, as it helps to download and cache the Kotlin/Native compiler binaries and
libraries with transitive dependencies and run the compiler and tests. Kotlin/Native can use the Gradle build system
through the kotlin-multiplatform plugin.
706
We covered the basics of setting up an IDE compatible project with Gradle in the A Basic Kotlin/Native Application
tutorial. Please check it out if you are looking for detailed first steps and instructions on how to start a new Kotlin/Native
project and open it in IntelliJ IDEA. In this tutorial, we'll look at the advanced C interop related usages of Kotlin/Native and
multiplatform builds with Gradle.
First, create a project folder. All the paths in this tutorial will be relative to this folder. Sometimes the missing directories
will have to be created before any new files can be added.
Kotlin
plugins {
kotlin("multiplatform") version "1.5.31"
}
repositories {
mavenCentral()
}
kotlin {
linuxX64("native") { // on Linux
// macosX64("native") { // on x86_64 macOS
// macosArm64("native") { // on Apple Silicon macOS
// mingwX64("native") { // on Windows
val main by compilations.getting
val interop by main.cinterops.creating
binaries {
executable()
}
}
}
tasks.wrapper {
gradleVersion = "6.7.1"
distributionType = Wrapper.DistributionType.BIN
}
Groovy
plugins {
id 'org.jetbrains.kotlin.multiplatform' version '1.5.31'
}
repositories {
mavenCentral()
}
kotlin {
linuxX64('native') { // on Linux
// macosX64("native") { // on x86_64 macOS
// macosArm64("native") { // on Apple Silicon macOS
// mingwX64('native') { // on Windows
compilations.main.cinterops {
707
interop
}
binaries {
executable()
}
}
}
wrapper {
gradleVersion = '6.7.1'
distributionType = 'BIN'
}
The project file configures the C interop as an additional step of the build. Let's move the interop.def file to the
src/nativeInterop/cinterop directory. Gradle recommends using conventions instead of configurations, for example, the
source files are expected to be in the src/nativeMain/kotlin folder. By default, all the symbols from C are imported to the
interop package, you may want to import the whole package in our .kt files. Check out the kotlin-multiplatform plugin
documentation to learn about all the different ways you could configure it.
Let's create a src/nativeMain/kotlin/hello.kt stub file with the following content to see how C primitive type declarations
are visible from Kotlin:
import interop.*
fun main() {
println("Hello Kotlin/Native!")
accept_fun(https://kotlinlang.org/*fix me */)
val useMe = supply_fun()
}
Now you are ready to open the project in IntelliJ IDEA and to see how to fix the example project. While doing that, see
how C functions are mapped into Kotlin/Native declarations.
C
function
pointers
in
Kotlin
With the help of IntelliJ IDEA's Go to | Declaration or compiler errors, see the following declarations for the C functions:
You see that the function's typedef from C has been turned into Kotlin typealias. It uses CPointer<..> type to represent
708
the pointer parameters, and CFunction<(Int)->Int> to represent the function signature. There is an invoke operator
extension function available for all CPointer<CFunction<..> types, so that it is possible to call it as you would call any
other function in Kotlin.
Pass
Kotlin
function
as
C
function
pointer
It is the time to try using C functions from the Kotlin program. Call the accept_fun function and pass the C function pointer
to a Kotlin lambda:
fun myFun() {
accept_fun(staticCFunction<Int, Int> { it + 1 })
}
This call uses the staticCFunction{..} helper function from Kotlin/Native to wrap a Kotlin lambda function into a C function
pointer. It only allows having unbound and non-capturing lambda functions. For example, it is not able to use a local
variable from the function. You may only use globally visible declarations. Throwing exceptions from a staticCFunction{..}
will end up in non-deterministic side-effects. It is vital to make sure that you code is not throwing any sudden exceptions
from it.
Use
the
C
function
pointer
from
Kotlin
The next step is to call a C function pointer from a C pointer that you have from the supply_fun() call:
fun myFun2() {
val functionFromC = supply_fun() ?: error("No function is returned")
functionFromC(42)
}
Kotlin turns the function pointer return type into a nullable CPointer<CFunction<..> object. There is the need to explicitly
check for null first. The elvis operator for that in the code above. The cinterop tool helps us to turn a C function pointer
into an easy to call object in Kotlin. This is what we did on the last line.
Fix
the
code
You've seen all definitions and it is time to fix and run the code. Run the runDebugExecutableNative Gradle task in the IDE
or use the following command to run the code:
./gradlew runDebugExecutableNative
709
import interop.*
import kotlinx.cinterop.*
fun main() {
println("Hello Kotlin/Native!")
val cFunctionPointer = staticCFunction<Int, Int> { it + 1 }
accept_fun(cFunctionPointer)
Next
Steps
Continue exploring more C language types and their representation in Kotlin/Native in next tutorials:
Mapping
Strings
from
C
–
tutorial
This is the last tutorial in the series. The first tutorial of the series is Mapping primitive data types from C. There are also
Mapping struct and union types from C and Mapping function pointers from C tutorials.
In this tutorial, you'll see how to deal with C strings in Kotlin/Native. You will learn how to:
Working
with
C
strings
There is no dedicated type in C language for strings. A developer knows from a method signature or the documentation,
whether a given char * means a C string in the context. Strings in the C language are null-terminated, a trailing zero
character \0 is added at the end of a bytes sequence to mark a string termination. Usually, UTF-8 encoded strings are
used. The UTF-8 encoding uses variable width characters, and it is backward compatible with ASCII. Kotlin/Native uses
UTF-8 character encoding by default.
The best way to understand the mapping between C and Kotlin languages is to try it out on a small example. Create a
710
small library headers for that. First, create a lib.h file with the following declaration of functions that deal with the C strings:
#ifndef LIB2_H_INCLUDED
#define LIB2_H_INCLUDED
#endif
In the example, you see the most popular ways to pass or receive a string in the C language. Take the return of
return_string with care. In general, it is best to make sure you use the right function to dispose the returned char* with the
right free(..) function call.
Kotlin/Native comes with the cinterop tool; the tool generates bindings between the C language and Kotlin. It uses a .def
file to specify a C library to import. More details on this are in the Interop with C Libraries tutorial. The quickest way to try
out C API mapping is to have all C declarations in the interop.def file, without creating any .h of .c files at all. Then place
the C declarations in a interop.def file after the special --- separator line:
headers = lib.h
---
char* return_string() {
return "C stirng";
}
The interop.def file is enough to compile and run the application or open it in an IDE. Now it is time to create project files,
open the project in IntelliJ IDEA and run it.
Inspect
generated
Kotlin
APIs
for
a
C
library
While it is possible to use the command line, either directly or by combining it with a script file (such as .sh or .bat file),
this approach doesn't scale well for big projects that have hundreds of files and libraries. It is then better to use the
Kotlin/Native compiler with a build system, as it helps to download and cache the Kotlin/Native compiler binaries and
libraries with transitive dependencies and run the compiler and tests. Kotlin/Native can use the Gradle build system
through the kotlin-multiplatform plugin.
711
We covered the basics of setting up an IDE compatible project with Gradle in the A Basic Kotlin/Native Application
tutorial. Please check it out if you are looking for detailed first steps and instructions on how to start a new Kotlin/Native
project and open it in IntelliJ IDEA. In this tutorial, we'll look at the advanced C interop related usages of Kotlin/Native and
multiplatform builds with Gradle.
First, create a project folder. All the paths in this tutorial will be relative to this folder. Sometimes the missing directories
will have to be created before any new files can be added.
Kotlin
plugins {
kotlin("multiplatform") version "1.5.31"
}
repositories {
mavenCentral()
}
kotlin {
linuxX64("native") { // on Linux
// macosX64("native") { // on x86_64 macOS
// macosArm64("native") { // on Apple Silicon macOS
// mingwX64("native") { // on Windows
val main by compilations.getting
val interop by main.cinterops.creating
binaries {
executable()
}
}
}
tasks.wrapper {
gradleVersion = "6.7.1"
distributionType = Wrapper.DistributionType.BIN
}
Groovy
plugins {
id 'org.jetbrains.kotlin.multiplatform' version '1.5.31'
}
repositories {
mavenCentral()
}
kotlin {
linuxX64('native') { // on Linux
// macosX64("native") { // on x86_64 macOS
// macosArm64("native") { // on Apple Silicon macOS
// mingwX64('native') { // on Windows
compilations.main.cinterops {
712
interop
}
binaries {
executable()
}
}
}
wrapper {
gradleVersion = '6.7.1'
distributionType = 'BIN'
}
The project file configures the C interop as an additional step of the build. Let's move the interop.def file to the
src/nativeInterop/cinterop directory. Gradle recommends using conventions instead of configurations, for example, the
source files are expected to be in the src/nativeMain/kotlin folder. By default, all the symbols from C are imported to the
interop package, you may want to import the whole package in our .kt files. Check out the kotlin-multiplatform plugin
documentation to learn about all the different ways you could configure it.
Let's create a src/nativeMain/kotlin/hello.kt stub file with the following content to see how C primitive type declarations
are visible from Kotlin:
import interop.*
fun main() {
println("Hello Kotlin/Native!")
pass_string(/*fix me*/)
val useMe = return_string()
val useMe2 = copy_string(/*fix me*/)
}
Now you are ready to open the project in IntelliJ IDEA and to see how to fix the example project. While doing that, see
how C primitive types are mapped into Kotlin/Native.
Primitive
types
in
Kotlin
With the help of IntelliJ IDEA's Go to | Declaration or compiler errors, you see the following generated API for the C
functions:
These declarations look clear. All char * pointers are turned into str: CValuesRef<ByteVar>? for parameters and to
CPointer<ByteVar>? in return types. Kotlin turns char type into kotlin.Byte type, as it is usually an 8-bit signed value.
In the generated Kotlin declarations, you see that str is represented as CValuesRef<ByteVar/>?. The type is nullable, and
713
you can simply pass Kotlin null as the parameter value.
Pass
Kotlin
string
to
C
Let's try to use the API from Kotlin. Call pass_string first:
fun passStringToC() {
val str = "this is a Kotlin String"
pass_string(str.cstr)
}
Passing a Kotlin string to C is easy, thanks to the fact that there is String.cstr extension property in Kotlin for it. There is
also String.wcstr for cases when you need UTF-16 wide characters.
Read
C
Strings
in
Kotlin
This time you'll take a returned char * from the return_string function and turn it into a Kotlin string. For that, do the
following in Kotlin:
fun passStringToC() {
val stringFromC = return_string()?.toKString()
println("Returned from C: $stringFromC")
}
This code uses the toKString() extension function above. Please do not miss out the toString() function. The toKString()
has two overloaded extension functions in Kotlin:
The first extension takes a char * as a UTF-8 string and turns it into a String. The second function does the same but for
wide UTF-16 strings.
Receive
C
string
bytes
from
Kotlin
This time we will ask a C function to write us a C string to a given buffer. The function is called copy_string. It takes a
pointer to the location writing characters and the allowed buffer size. The function returns something to indicate if it has
succeeded or failed. Let's assume 0 means it succeeded, and the supplied buffer was big enough:
fun sendString() {
val buf = ByteArray(255)
buf.usePinned { pinned ->
if (copy_string(pinned.addressOf(0), buf.size - 1) != 0) {
714
throw Error("Failed to read string from C")
}
}
First of all, you need to have a native pointer to pass to the C function. Use the usePinned extension function to
temporarily pin the native memory address of the byte array. The C function fills in the byte array with data. Use another
extension function ByteArray.stringFromUtf8() to turn the byte array into a Kotlin String, assuming UTF-8 encoding.
Fix
the
Code
You've now seen all the definitions and it is time to fix the code. Run the runDebugExecutableNative Gradle task in the
IDE or use the following command to run the code:
./gradlew runDebugExecutableNative
The code in the final hello.kt file may look like this:
import interop.*
import kotlinx.cinterop.*
fun main() {
println("Hello Kotlin/Native!")
println(copyFromC)
}
Next
steps
Continue to explore more C language types and their representation in Kotlin/Native in our other tutorials:
715
Mapping struct and union types from C
The C Interop documentation documentation covers more advanced scenarios of the interop.
Using
C
Interop
and
libcurl
for
an
app
–
tutorial
When writing native applications, oftentimes you need to access certain functionality that is not included in the Kotlin
standard library, such as making HTTP requests, reading and writing from disk, etc.
Kotlin/Native provides you with the ability to consume standard C libraries, opening up an entire ecosystem of
functionality that exists for pretty much anything you could need. In fact, Kotlin/Native already ships with a set of prebuilt
platform libraries which provide some additional common functionality to that of the standard library.
In this tutorial, you'll see how to use some specific libraries, such as libcurl. You'll learn to:
Generate
bindings
An ideal scenario for interop is to call C functions as if you were calling Kotlin functions, that is, following the same
signature and conventions. This is precisely what the cinterop tool provides. It takes a C library and generates the
corresponding Kotlin bindings for it, which then allows you to use the library as if it were Kotlin code.
In order to generate these bindings, you need to create a library definition .def file that contains some information about
the headers you need to generate. In this case, you'll use the famous libcurl library to make some HTTP calls, so create a
file named libcurl.def with the following contents:
headers = curl/curl.h
headerFilter = curl/*
A few things are going on in this file, let's go through them one by one. The first entry is headers which is the list of
header files that you want to generate Kotlin stubs for. You can add multiple files to this entry, separating each one with a
\ on a new line. For this tutorial, you'll only need curl.h. The files we are referencing need to be relative to the folder where
the definition file is, or be available on the system path (/usr/include/curl).
716
The second line is the headerFilter. This is used to denote what exactly we want included. In C, when one file references
another file with the #include directive, all the headers are also included. Sometimes this may not be needed, and you can
use this parameter, using glob patterns, to fine tune things. Note, that headerFilter is an optional argument and mostly
only used when the library you're using is being installed as a system library, and you do not want to fetch external
dependencies (such as system stdint.h header) into your interop library. It may be important for both optimizing the library
size and fixing potential conflicts between the system and the Kotlin/Native provided compilation environment.
The next lines are about providing linker and compiler options, which can vary depending on different target platforms. In
this tutorial, we are defining it for macOS (the .osx suffix) and Linux (the .linux suffix). Parameters without a suffix is also
possible (e.g. linkerOpts=) and will be applied to all platforms.
The convention that is followed is that each library gets its own definition file, usually named the same as the library. For
more information on all the options available to cinterop, see the Interop documentation
Once you have the definition file ready, create project files and open the project in an IDE.
While it is possible to use the command line, either directly or by combining it with a script file (such as .sh or .bat file),
this approach doesn't scale well for big projects that have hundreds of files and libraries. It is then better to use the
Kotlin/Native compiler with a build system, as it helps to download and cache the Kotlin/Native compiler binaries and
libraries with transitive dependencies and run the compiler and tests. Kotlin/Native can use the Gradle build system
through the kotlin-multiplatform plugin.
We covered the basics of setting up an IDE compatible project with Gradle in the A Basic Kotlin/Native Application
tutorial. Please check it out if you are looking for detailed first steps and instructions on how to start a new Kotlin/Native
project and open it in IntelliJ IDEA. In this tutorial, we'll look at the advanced C interop related usages of Kotlin/Native and
multiplatform builds with Gradle.
First, create a project folder. All the paths in this tutorial will be relative to this folder. Sometimes the missing directories
will have to be created before any new files can be added.
Kotlin
plugins {
kotlin("multiplatform") version "1.5.31"
}
repositories {
mavenCentral()
}
kotlin {
linuxX64("native") { // on Linux
// macosX64("native") { // on x86_64 macOS
// macosArm64("native") { // on Apple Silicon macOS
// mingwX64("native") { // on Windows
val main by compilations.getting
val interop by main.cinterops.creating
binaries {
executable()
717
}
}
}
tasks.wrapper {
gradleVersion = "6.7.1"
distributionType = Wrapper.DistributionType.ALL
}
Groovy
plugins {
id 'org.jetbrains.kotlin.multiplatform' version '1.5.31'
}
repositories {
mavenCentral()
}
kotlin {
linuxX64("native") { // on Linux
// macosX64("native") { // on x86_64 macOS
// macosArm64("native") { // on Apple Silicon macOS
// mingwX64("native") { // on Windows
compilations.main.cinterops {
interop
}
binaries {
executable()
}
}
}
wrapper {
gradleVersion = "6.7.1"
distributionType = "ALL"
}
The project file configures the C interop as an additional step of the build. Let's move the interop.def file to the
src/nativeInterop/cinterop directory. Gradle recommends using conventions instead of configurations, for example, the
source files are expected to be in the src/nativeMain/kotlin folder. By default, all the symbols from C are imported to the
interop package, you may want to import the whole package in our .kt files. Check out the kotlin-multiplatform plugin
documentation to learn about all the different ways you could configure it.
curl
on
Windows
You should have the curl library binaries on Windows to make the sample work. You may build curl from sources on
Windows (you'll need Visual Studio or Windows SDK Commandline tools), for more details, see the related blog post.
Alternatively, you may also want to consider a MinGW/MSYS2 curl binary.
718
Consume
the
Kotlin
API
Now you have the library and Kotlin stubs and can consume them from our application. To keep things simple, in this
tutorial you're going to convert one of the simplest libcurl examples over to Kotlin.
The code in question is from the simple example (comments removed for brevity):
#include <stdio.h>
#include <curl/curl.h>
int main(void)
{
CURL *curl;
CURLcode res;
curl = curl_easy_init();
if(curl) {
curl_easy_setopt(curl, CURLOPT_URL, "https://example.com");
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
res = curl_easy_perform(curl);
if(res != CURLE_OK)
fprintf(stderr, "curl_easy_perform() failed: %s\n",
curl_easy_strerror(res));
curl_easy_cleanup(curl);
}
return 0;
}
The first thing you'll need is a Kotlin file called src/nativeMain/kotlin/hello.kt with the main function defined in it and then
proceed to translate each line.
import interop.*
import kotlinx.cinterop.*
As you can see, you've eliminated the explicit variable declarations in the Kotlin version, but everything else is pretty much
verbatim to the C version. All the calls you'd expect in the libcurl library are available in their Kotlin equivalent.
Note that for the purpose of this tutorial, we've done a line by line literal translation. Obviously you could write this in a
more Kotlin idiomatic way.
719
Compile
and
link
the
library
The next step is to compile the application. We already covered the basics of compiling a Kotlin/Native application from
the command line in the A Basic Kotlin/Native application tutorial. The only difference in this case is that the cinterop
generated part is implicitly included into the build: Call the following command:
./gradlew runDebugExecutableNative
If there are no errors during compilation, you should see the result of the execution of the program, which on execution
should output the contents of the site https://example.com
Output
The reason you're seeing the actual output is because the call curl_easy_perform prints the result to the standard output.
You could hide this using curl_easy_setopt.
For a more complete example of using libcurl, the libcurl sample of the Kotlin/Native project shows how to abstract the
code into Kotlin classes as well as display headers. It also demonstrates how to make the steps a little easier by
combining them into a shell script or Gradle build.
Interoperability
with
Swift/Objective-C
This document covers some details of Kotlin/Native interoperability with Swift/Objective-C.
720
Usage
Kotlin/Native provides bidirectional interoperability with Objective-C. Objective-C frameworks and libraries can be used in
Kotlin code if properly imported to the build (system frameworks are imported by default). See compilation configurations
for more details. A Swift library can be used in Kotlin code if its API is exported to Objective-C with @objc. Pure Swift
modules are not yet supported.
Kotlin modules can be used in Swift/Objective-C code if compiled into a framework (see here for how to declare binaries).
See calculator sample for an example.
Mappings
The table below shows how Kotlin concepts are mapped to Swift/Objective-C and vice versa.
"->" and "<-" indicate that mapping only goes one way.
721
Kotlin Swift Objective-C Notes
Name
translation
Objective-C classes are imported into Kotlin with their original names. Protocols are imported as interfaces with Protocol
name suffix, i.e. @protocol Foo -> interface FooProtocol. These classes and interfaces are placed into a package
specified in build configuration (platform.* packages for preconfigured system frameworks).
The names of Kotlin classes and interfaces are prefixed when imported to Objective-C. The prefix is derived from the
framework name.
Initializers
Swift/Objective-C initializers are imported to Kotlin as constructors and factory methods named create. The latter
happens with initializers declared in the Objective-C category or as a Swift extension, because Kotlin has no concept of
extension constructors.
Setters
Writeable Objective-C properties overriding read-only properties of the superclass are represented as setFoo() method for
the property foo. Same goes for a protocol's read-only properties that are implemented as mutable.
722
Top-level
functions
and
properties
Top-level Kotlin functions and properties are accessible as members of special classes. Each Kotlin file is translated into
such a class. E.g.
// MyLibraryUtils.kt
package my.library
fun foo() {}
MyLibraryUtilsKt.foo()
Method
names
translation
Generally Swift argument labels and Objective-C selector pieces are mapped to Kotlin parameter names. Anyway these
two concepts have different semantics, so sometimes Swift/Objective-C methods can be imported with a clashing Kotlin
signature. In this case the clashing methods can be called from Kotlin using named arguments, e.g.:
Errors
and
exceptions
Kotlin has no concept of checked exceptions, all Kotlin exceptions are unchecked. Swift has only checked errors. So if
Swift or Objective-C code calls a Kotlin method which throws an exception to be handled, then the Kotlin method should
be marked with a @Throws annotation specifying a list of "expected" exception classes.
When compiling to Objective-C/Swift framework, non- suspend functions having or inheriting @Throws annotation are
represented as NSError* -producing methods in Objective-C and as throws methods in Swift. Representations for
suspend functions always have NSError*/ Error parameter in completion handler.
When Kotlin function called from Swift/Objective-C code throws an exception which is an instance of one of the @Throws
-specified classes or their subclasses, it is propagated as NSError. Other Kotlin exceptions reaching Swift/Objective-C are
considered unhandled and cause program termination.
suspend functions without @Throws propagate only CancellationException as NSError. Non- suspend functions without
@Throws don't propagate Kotlin exceptions at all.
Note that the opposite reversed translation is not implemented yet: Swift/Objective-C error-throwing methods aren't
imported to Kotlin as exception-throwing.
723
Suspending
functions
Support for calling suspend functions from Swift code as async is Experimental. It may be dropped or changed
at any time. Use it only for evaluation purposes. We would appreciate your feedback on it in YouTrack.
Kotlin's suspending functions (suspend) are presented in the generated Objective-C headers as functions with callbacks,
or completion handlers in Swift/Objective-C terminology.
Starting from Swift 5.5, Kotlin's suspend functions are also available for calling from Swift as async functions without
using the completion handlers. Currently, this functionality is highly experimental and has certain limitations. See this
YouTrack issue for details.
Extensions
and
category
members
Members of Objective-C categories and Swift extensions are imported to Kotlin as extensions. That's why these
declarations can't be overridden in Kotlin. And the extension initializers aren't available as Kotlin constructors.
Kotlin extensions to "regular" Kotlin classes are imported to Swift and Objective-C as extensions and category members
respectively. Kotlin extensions to other types are treated as top-level declarations with an additional receiver parameter.
These types include:
Kotlin
singletons
Kotlin singleton (made with an object declaration, including companion object) is imported to Swift/Objective-C as a class
with a single instance.
724
object MyObject {
val x = "Some value"
}
class MyClass {
companion object {
val x = "Some value"
}
}
MyObject.shared
MyObject.shared.x
MyClass.companion
MyClass.Companion.shared
Access objects through [MySingleton mySingleton] in Objective-C and MySingleton() in Swift has been
deprecated.
NSNumber
Kotlin primitive type boxes are mapped to special Swift/Objective-C classes. For example, kotlin.Int box is represented as
KotlinInt class instance in Swift (or ${prefix}Int instance in Objective-C, where prefix is the framework names prefix). These
classes are derived from NSNumber, so the instances are proper NSNumber s supporting all corresponding operations.
NSNumber type is not automatically translated to Kotlin primitive types when used as a Swift/Objective-C parameter type
or return value. The reason is that NSNumber type doesn't provide enough information about a wrapped primitive value
type, i.e. NSNumber is statically not known to be a e.g. Byte, Boolean, or Double. So Kotlin primitive values should be
cast to/from NSNumber manually (see below).
NSMutableString
NSMutableString Objective-C class is not available from Kotlin. All instances of NSMutableString are copied when passed
to Kotlin.
Collections
Kotlin collections are converted to Swift/Objective-C collections as described in the table above. Swift/Objective-C
collections are mapped to Kotlin in the same way, except for NSMutableSet and NSMutableDictionary. NSMutableSet
isn't converted to a Kotlin MutableSet. To pass an object for Kotlin MutableSet, you can create this kind of Kotlin
collection explicitly by either creating it in Kotlin with e.g. mutableSetOf(), or using the KotlinMutableSet class in Swift (or
${prefix}MutableSet in Objective-C, where prefix is the framework names prefix). The same holds for MutableMap.
Function
types
725
Kotlin function-typed objects (e.g. lambdas) are converted to Swift functions / Objective-C blocks. However there is a
difference in how types of parameters and return values are mapped when translating a function and a function type. In
the latter case primitive types are mapped to their boxed representation. Kotlin Unit return value is represented as a
corresponding Unit singleton in Swift/Objective-C. The value of this singleton can be retrieved in the same way as it is for
any other Kotlin object (see singletons in the table above). To sum the things up:
foo {
bar($0 as! Int32)
return KotlinUnit()
}
Generics
Objective-C supports "lightweight generics" defined on classes, with a relatively limited feature set. Swift can import
generics defined on classes to help provide additional type information to the compiler.
Generic feature support for Objective-C and Swift differ from Kotlin, so the translation will inevitably lose some
information, but the features supported retain meaningful information.
Limitations
Objective-C generics do not support all features of either Kotlin or Swift, so there will be some information lost in the
translation.
Generics can only be defined on classes, not on interfaces (protocols in Objective-C and Swift) or functions.
Nullability
Kotlin and Swift both define nullability as part of the type specification, while Objective-C defines nullability on methods
and properties of a type. As such, the following:
class Sample<T>() {
fun myVal(): T
}
class Sample<T>() {
726
fun myVal(): T?
}
In order to support a potentially nullable type, the Objective-C header needs to define myVal with a nullable return value.
To mitigate this, when defining your generic classes, if the generic type should never be null, provide a non-null type
constraint:
Variance
Objective-C allows generics to be declared covariant or contravariant. Swift has no support for variance. Generic classes
coming from Objective-C can be force-cast as needed.
Constraints
In Kotlin you can provide upper bounds for a generic type. Objective-C also supports this, but that support is unavailable
in more complex cases, and is currently not supported in the Kotlin - Objective-C interop. The exception here being a
non-null upper bound will make Objective-C methods/properties non-null.
To disable
To have the framework header written without generics, add the flag to the compiler config:
binaries.framework {
freeCompilerArgs += "-Xno-objc-generics"
}
Casting
between
mapped
types
When writing Kotlin code, an object may need to be converted from a Kotlin type to the equivalent Swift/Objective-C type
(or vice versa). In this case a plain old Kotlin cast can be used, e.g.
727
val string = nsString as String
val nsNumber = 42 as NSNumber
Subclassing
Subclassing
Kotlin
classes
and
interfaces
from
Swift/Objective-C
Kotlin classes and interfaces can be subclassed by Swift/Objective-C classes and protocols.
Subclassing
Swift/Objective-C
classes
and
protocols
from
Kotlin
Swift/Objective-C classes and protocols can be subclassed with a Kotlin final class. Non- final Kotlin classes inheriting
Swift/Objective-C types aren't supported yet, so it is not possible to declare a complex class hierarchy inheriting
Swift/Objective-C types.
Normal methods can be overridden using the override Kotlin keyword. In this case the overriding method must have the
same parameter names as the overridden one.
Sometimes it is required to override initializers, e.g. when subclassing UIViewController. Initializers imported as Kotlin
constructors can be overridden by Kotlin constructors marked with the @OverrideInit annotation:
...
}
The overriding constructor must have the same parameter names and types as the overridden one.
To override different methods with clashing Kotlin signatures, you can add a @Suppress("CONFLICTING_OVERLOADS")
annotation to the class.
By default the Kotlin/Native compiler doesn't allow calling a non-designated Objective-C initializer as a super(...)
constructor. This behaviour can be inconvenient if the designated initializers aren't marked properly in the Objective-C
library. Adding a disableDesignatedInitializerChecks = true to the .def file for this library would disable these compiler
checks.
C
features
See Interoperability with C for an example case where the library uses some plain C features, such as unsafe pointers,
structs, and so on.
Unsupported
728
Some features of Kotlin programming language are not yet mapped into respective features of Objective-C or Swift.
Currently, following features are not properly exposed in generated framework headers:
inline classes (arguments are mapped as either underlying primitive type or id)
custom classes implementing standard Kotlin collection interfaces (List, Map, Set) and other special classes
CocoaPods
integration
Kotlin/Native provides integration with the CocoaPods dependency manager. You can add dependencies on Pod libraries
as well as use a multiplatform project with native targets as a CocoaPods dependency (Kotlin Pod).
You can manage Pod dependencies directly in IntelliJ IDEA and enjoy all the additional features such as code highlighting
and completion. You can build the whole Kotlin project with Gradle and not ever have to switch to Xcode.
Use Xcode only when you need to write Swift/Objective-C code or run your application on a simulator or device. To work
correctly with Xcode, you should update your Podfile.
Depending on your project and purposes, you can add dependencies between a Kotlin project and a Pod library as well
as a Kotlin Pod and an Xcode project.
You can also add dependencies between a Kotlin Pod and multiple Xcode projects. However, in this case you
need to add a dependency by calling pod install manually for each Xcode project. In other cases, it's done
automatically.
Install
the
CocoaPods
dependency
manager
and
plugin
1. Install the CocoaPods dependency manager.
3. In build.gradle.kts (or build.gradle) of your IDEA project, apply the CocoaPods plugin as well as the Kotlin
Multiplatform plugin.
plugins {
kotlin("multiplatform") version "1.5.31"
kotlin("native.cocoapods") version "1.5.31"
729
}
4. Configure summary, homepage, and frameworkName of the Podspec file in the cocoapods block.
version is a version of the Gradle project.
plugins {
kotlin("multiplatform") version "1.5.31"
kotlin("native.cocoapods") version "1.5.31"
}
kotlin {
cocoapods {
framework {
// Configure fields required by CocoaPods.
summary = "Some description for a Kotlin/Native module"
homepage = "Link to a Kotlin/Native module homepage"
// Framework name configuration. Use this property instead of deprecated
'frameworkName'
baseName = "MyFramework"
// (Optional) Dynamic framework support
isStatic = false
// (Optional) Dependency export
export(project(":anotherKMMModule"))
transitiveExport = true
// (Optional) Bitcode embedding
embedBitcode(BITCODE)
}
6. Generate the Gradle wrapper to avoid compatibility issues during an Xcode build.
Adds both debug and release frameworks as output binaries for all macOS, iOS, tvOS, and watchOS targets.
Creates a podspec task which generates a Podspec file for the project.
The Podspec file includes a path to an output framework and script phases that automate building this framework during
the build process of an Xcode project.
Add
dependencies
on
Pod
libraries
To add dependencies between a Kotlin project and a Pod library, you should complete the initial configuration. This
730
allows you to add dependencies on the following types of Pod libraries:
A Kotlin project requires the pod() function call in build.gradle.kts (build.gradle) for adding a Pod dependency. Each
dependency requires its own separate function call. You can specify the parameters for the dependency in the
configuration block of the function.
When you add a new dependency and re-import the project in IntelliJ IDEA, the new dependency will be added
automatically. No additional steps are required.
To use your Kotlin project with Xcode, you should make changes in your project Podfile.
Add
a
dependency
on
a
Pod
library
from
the
CocoaPods
repository
You can add dependencies on a Pod library from the CocoaPods repository with pod() to build.gradle.kts (build.gradle) of
your project:
1. Specify the name of a Pod library in the pod() function. In the configuration block you can specify the version of the
library using the version parameter. To use the latest version of the library, you can just omit this parameter all-
together.
2. Specify the minimum deployment target version for the Pod library.
If you don't specify the minimum deployment target version and a dependency Pod requires a higher
deployment target, you will get an error.
kotlin {
ios()
cocoapods {
ios.deploymentTarget = "13.5"
731
summary = "CocoaPods test library"
homepage = "https://github.com/JetBrains/kotlin"
pod("AFNetworking") {
version = "~> 4.0.1"
}
}
}
To use these dependencies from the Kotlin code, import the packages cocoapods.<library-name>.
import cocoapods.AFNetworking.*
Add
a
dependency
on
a
Pod
library
stored
locally
You can add a dependency on a Pod library stored locally with pod() to build.gradle.kts (build.gradle) of your project:
1. Specify the name of a Pod library in the pod() function. In the configuration block specify the path to the local Pod
library: use the path() function in the source parameter value.
You can add local dependencies on subspecs as well. The cocoapods block can include dependencies to
Pods stored locally and Pods from the CocoaPods repository at the same time.
2. Specify the minimum deployment target version for the Pod library.
If you don't specify the minimum deployment target version and a dependency Pod requires a higher
deployment target, you will get an error.
kotlin {
ios()
cocoapods {
summary = "CocoaPods test library"
homepage = "https://github.com/JetBrains/kotlin"
ios.deploymentTarget = "13.5"
pod("pod_dependency") {
version = "1.0"
source = path(project.file("../pod_dependency/pod_dependency.podspec"))
}
pod("subspec_dependency/Core") {
version = "1.0"
source = path(project.file("../subspec_dependency/subspec_dependency.podspec"))
732
}
pod("AFNetworking") {
version = "~> 4.0.1"
}
}
}
You can also specify the version of the library using version parameter in the configuration block. To use the
latest version of the library, omit the parameter.
To use these dependencies from the Kotlin code, import the packages cocoapods.<library-name>.
import cocoapods.pod_dependency.*
import cocoapods.subspec_dependency.*
import cocoapods.AFNetworking.*
Add
a
dependency
on
a
Pod
library
from
the
Git
repository
You can add dependencies on a Pod library from a custom Git repository with pod() to build.gradle.kts (build.gradle) of
your project:
1. Specify the name of a Pod library in the pod() function. In the configuration block specify the path to the git repository:
use the git() function in the source parameter value.
Additionally, you can specify the following parameters in the block after git():
The git() function prioritizes passed parameters in the following order: commit, tag, branch. If you don't specify a
parameter, the Kotlin plugin uses HEAD from the master branch.
You can combine branch, commit, and tag parameters to get the specific version of a Pod.
2. Specify the minimum deployment target version for the Pod library.
733
If you don't specify the minimum deployment target version and a dependency Pod requires a higher
deployment target, you will get an error.
kotlin {
ios()
cocoapods {
summary = "CocoaPods test library"
homepage = "https://github.com/JetBrains/kotlin"
ios.deploymentTarget = "13.5"
pod("AFNetworking") {
source = git("https://github.com/AFNetworking/AFNetworking") {
tag = "4.0.0"
}
}
pod("JSONModel") {
source = git("https://github.com/jsonmodel/jsonmodel.git") {
branch = "key-mapper-class"
}
}
pod("CocoaLumberjack") {
source = git("https://github.com/CocoaLumberjack/CocoaLumberjack.git") {
commit = "3e7f595e3a459c39b917aacf9856cd2a48c4dbf3"
}
}
}
}
To work correctly with Xcode, you should specify the path to the Podspec in your Podfile. For example:
target 'ios-app' do
# ... other pod depedencies ...
pod 'JSONModel', :path => '../cocoapods/kmm-with-cocoapods-sample/kotlin-
library/build/cocoapods/externalSources/git/JSONModel'
end
To use these dependencies from the Kotlin code, import the packages cocoapods.<library-name>.
import cocoapods.AFNetworking.*
import cocoapods.JSONModel.*
import cocoapods.CocoaLumberjack.*
734
Add
a
dependency
on
a
Pod
library
from
an
archive
You can add dependencies on a Pod library from zip, tar, or jar archive with pod() to build.gradle.kts (build.gradle) of your
project:
1. Specify the name of a Pod library in the pod() function. In the configuration block specify the path to the archive: use
the url() function with an arbitrary HTTP address in the source parameter value.
Additionally, you can specify the boolean flatten parameter as a second argument for the url() function. This parameter
indicates that all the Pod files are located in the root directory of the archive.
2. Specify the minimum deployment target version for the Pod library.
If you don't specify the minimum deployment target version and a dependency Pod requires a higher
deployment target, you will get an error.
kotlin {
ios()
cocoapods {
summary = "CocoaPods test library"
homepage = "https://github.com/JetBrains/kotlin"
ios.deploymentTarget = "13.5"
pod("pod_dependency") {
source = url("https://github.com/Kotlin/kmm-with-cocoapods-sample/raw/cocoapods-
zip/cocoapodSourcesZip.zip", flatten = true)
}
}
}
To work correctly with Xcode, you should specify the path to the Podspec in your Podfile. For example:
target 'ios-app' do
# ... other pod depedencies ...
pod 'podspecWithFilesExample', :path => '../cocoapods/kmm-with-cocoapods-
sample/pod_dependency'
end
To use these dependencies from the Kotlin code, import the packages cocoapods.<library-name>.
735
import cocoapods.pod_dependency.*
Add
a
dependency
on
a
Pod
library
from
a
custom
Podspec
repository
You can add dependencies on a Pod library from a custom Podspec repository with pod() and specRepos to
build.gradle.kts (build.gradle) of your project:
1. Specify the HTTP address to the custom Podspec repository using the url() inside the specRepos block.
3. Specify the minimum deployment target version for the Pod library.
If you don't specify the minimum deployment target version and a dependency Pod requires a higher
deployment target, you will get an error.
kotlin {
ios()
cocoapods {
summary = "CocoaPods test library"
homepage = "https://github.com/JetBrains/kotlin"
ios.deploymentTarget = "13.5"
specRepos {
url("https://github.com/Kotlin/kotlin-cocoapods-spec.git")
}
pod("example")
}
}
736
To work correctly with Xcode, you should specify the location of specs at the beginning of your Podfile. For
example,
source 'https://github.com/Kotlin/kotlin-cocoapods-spec.git'`
You should also specify the path to the Podspec in your Podfile. For example:
target 'ios-app' do
# ... other pod depedencies ...
pod 'podspecWithFilesExample', :path => '../cocoapods/kmm-with-cocoapods-
sample/pod_dependency'
end
To use these dependencies from the Kotlin code, import the packages cocoapods.<library-name>.
import cocoapods.example.*
Add
a
dependency
on
a
Pod
library
with
custom
cinterop
options
You can add dependencies on a Pod library with custom cinterop options with pod() to build.gradle.kts (build.gradle) of
your project:
1. Specify the name of a Pod library in the pod() function. In the configuration block specify the cinterop options:
extraOpts – to specify the list of options for a Pod library. For example, specific flags: extraOpts = listOf("-
compiler-option")
packageName – to specify the package name. If you specify this, you can import the library using the package
name: import <packageName>.
2. Specify the minimum deployment target version for the Pod library.
If you don't specify the minimum deployment target version and a dependency Pod requires a higher
deployment target, you will get an error.
kotlin {
ios()
cocoapods {
summary = "CocoaPods test library"
homepage = "https://github.com/JetBrains/kotlin"
737
ios.deploymentTarget = "13.5"
useLibraries()
pod("YandexMapKit") {
packageName = "YandexMK"
}
}
}
To use these dependencies from the Kotlin code, import the packages cocoapods.<library-name>.
import cocoapods.YandexMapKit.*
If you use the packageName parameter, you can import the library using the package name import <packageName>:
import YandexMK.YMKPoint
import YandexMK.YMKDistance
Add
a
dependency
on
a
static
Pod
library
You can add dependencies on a static Pod library with pod() and useLibraries() to build.gradle.kts (build.gradle) of your
project:
2. Call the useLibraries() function – it enables a special flag for static libraries.
3. Specify the minimum deployment target version for the Pod library.
If you don't specify the minimum deployment target version and a dependency Pod requires a higher
deployment target, you will get an error.
kotlin {
ios()
cocoapods {
summary = "CocoaPods test library"
homepage = "https://github.com/JetBrains/kotlin"
ios.deploymentTarget = "13.5"
pod("YandexMapKit") {
version = "~> 3.2"
}
useLibraries()
}
738
}
To use these dependencies from the Kotlin code, import the packages cocoapods.<library-name>.
import cocoapods.YandexMapKit.*
Update
Podfile
for
Xcode
If you want to import your Kotlin project in an Xcode project, you’ll need to make some changes to your Podfile for it
to work correctly:
If your project has any Git, HTTP, or custom Podspec repository dependencies, you should also specify the path to the
Podspec in the Podfile.
For example, if you add a dependency on podspecWithFilesExample, declare the path to the Podspec in the Podfile:
target 'ios-app' do
# ... other depedencies ...
pod 'podspecWithFilesExample', :path =>
'cocoapods/externalSources/url/podspecWithFilesExample'
end
When you add a library from the custom Podspec repository, you should also specify the location of specs at the
beginning of your Podfile:
source 'https://github.com/Kotlin/kotlin-cocoapods-spec.git'
target 'kotlin-cocoapods-xcproj' do
# ... other depedencies ...
pod 'example'
end
If you don't make these changes to the Podfile, the podInstall task will fail and the CocoaPods plugin will show an error
message in the log.
Check out the withXcproject branch of the sample project, which contains an example of Xcode integration with an
existing Xcode project named kotlin-cocoapods-xcproj.
Use
a
Kotlin
Gradle
project
as
a
CocoaPods
dependency
739
You can use a Kotlin Multiplatform project with native targets as a CocoaPods dependency (Kotlin Pod). You can include
such a dependency in the Podfile of the Xcode project by its name and path to the project directory containing the
generated Podspec. This dependency will be automatically built (and rebuilt) along with this project. Such an approach
simplifies importing to Xcode by removing a need to write the corresponding Gradle tasks and Xcode build steps
manually.
To correctly import the dependencies into the Kotlin/Native module, the Podfile must contain either
use_modular_headers! or use_frameworks! directive.
Add
a
dependency
between
a
Kotlin
Pod
and
Xcode
project
with
one
target
1. Create an Xcode project with a Podfile if you haven’t done so yet.
2. Add the path to your Xcode project Podfile with podfile = project.file(..) to build.gradle.kts (build.gradle) of your Kotlin
project. This step helps synchronize your Xcode project with Kotlin Pod dependencies by calling pod install for your
Podfile.
If you don't specify the minimum target version and a dependency Pod requires a higher deployment target,
you will get an error.
kotlin {
ios()
cocoapods {
summary = "CocoaPods test library"
homepage = "https://github.com/JetBrains/kotlin"
ios.deploymentTarget = "13.5"
pod("AFNetworking") {
version = "~> 4.0.0"
}
podfile = project.file("../ios-app/Podfile")
}
}
4. Add the name and path of the Kotlin Pod you want to include in the Xcode project to Podfile.
use_frameworks!
740
target 'ios-app' do
pod 'kotlin_library', :path => '../kotlin-library'
end
Add
a
dependency
between
a
Kotlin
Pod
with
an
Xcode
project
with
several
targets
1. Create an Xcode project with a Podfile if you haven’t done so yet.
2. Add the path to your Xcode project Podfile with podfile = project.file(..) to build.gradle.kts (build.gradle) of your Kotlin
project. This step helps synchronize your Xcode project with Kotlin Pod dependencies by calling pod install for your
Podfile.
3. Add dependencies to the Pod libraries that you want to use in your project with pod().
4. For each target, specify the minimum target version for the Pod library.
If you don't specify the minimum deployment target version and a dependency Pod requires a higher
deployment target, you will get an error.
kotlin {
ios()
tvos()
cocoapods {
summary = "CocoaPods test library"
homepage = "https://github.com/JetBrains/kotlin"
ios.deploymentTarget = "13.5"
tvos.deploymentTarget = "13.4"
pod("AFNetworking") {
version = "~> 4.0.0"
}
podfile = project.file("../severalTargetsXcodeProject/Podfile") // specify the path to
Podfile
}
}
5. Add the name and path of the Kotlin Pod you want to include in the Xcode project to the Podfile.
target 'iosApp' do
use_frameworks!
platform :ios, '13.5'
# Pods for iosApp
pod 'kotlin_library', :path => '../kotlin-library'
end
target 'TVosApp' do
use_frameworks!
741
platform :tvos, '13.4'
Kotlin/Native
as
an
Apple
framework
–
tutorial
Kotlin/Native provides bi-directional interoperability with Objective-C/Swift. Objective-C frameworks and libraries can be
used in Kotlin code. Kotlin modules can be used in Swift/Objective-C code too. Besides that, Kotlin/Native has C Interop.
There is also the Kotlin/Native as a Dynamic Library tutorial for more information.
In this tutorial, you will see how to use Kotlin/Native code from Objective-C and Swift applications on macOS and iOS.
Create
a
Kotlin
library
The Kotlin/Native compiler can produce a framework for macOS and iOS out of the Kotlin code. The created framework
contains all declarations and binaries needed to use it with Objective-C and Swift. The best way to understand the
techniques is to try it for ourselves. Let's create a tiny Kotlin library first and use it from an Objective-C program.
package example
object Object {
val field = "A"
}
interface Interface {
fun iMember() {}
}
742
fun forIntegers(b: Byte, s: UShort, i: Int, l: ULong?) { }
fun forFloats(f: Float, d: Double?) { }
While it is possible to use the command line, either directly or by combining it with a script file (such as .sh or .bat file),
this approach doesn't scale well for big projects that have hundreds of files and libraries. It is therefore better to use the
Kotlin/Native compiler with a build system, as it helps to download and cache the Kotlin/Native compiler binaries and
libraries with transitive dependencies and run the compiler and tests. Kotlin/Native can use the Gradle build system
through the kotlin-multiplatform plugin.
We covered the basics of setting up an IDE compatible project with Gradle in the A Basic Kotlin/Native Application
tutorial. Please check it out if you are looking for detailed first steps and instructions on how to start a new Kotlin/Native
project and open it in IntelliJ IDEA. In this tutorial, we'll look at the advanced C interop related usages of Kotlin/Native and
multiplatform builds with Gradle.
First, create a project folder. All the paths in this tutorial will be relative to this folder. Sometimes the missing directories
will have to be created before any new files can be added.
Kotlin
plugins {
kotlin("multiplatform") version "1.5.31"
}
repositories {
mavenCentral()
}
kotlin {
macosX64("native") {
binaries {
framework {
baseName = "Demo"
}
}
}
}
tasks.wrapper {
gradleVersion = "6.7.1"
distributionType = Wrapper.DistributionType.ALL
}
Groovy
743
plugins {
id 'org.jetbrains.kotlin.multiplatform' version '1.5.31'
}
repositories {
mavenCentral()
}
kotlin {
macosX64("native") {
binaries {
framework {
baseName = "Demo"
}
}
}
}
wrapper {
gradleVersion = "6.7.1"
distributionType = "ALL"
}
Move the sources file into the src/nativeMain/kotlin folder under the project. That is the default path, where sources are
located, when the kotlin-multiplatform plugin is used. Use the following block to configure the project to generate a
dynamic or shared library:
binaries {
framework {
baseName = "Demo"
}
}
Along with macOS X64, Kotlin/Native supports macos arm64 and iOS arm32, arm64 and X64 targets. You may replace
the macosX64 with respective functions as shown in the table:
Run the linkNative Gradle task to build the library in the IDE or by calling the following console command:
744
./gradlew linkNative
Depending on the variant, the build generates the framework into the build/bin/native/debugFramework and
build/bin/native/releaseFramework folders. Let's see what is inside.
Generated
framework
headers
Each of the created frameworks contains the header file in <Framework>/Headers/Demo.h. The headers do not depend
on the target platform (at least with Kotlin/Native v.0.9.2). It contains the definitions for our Kotlin code and a few Kotlin-
wide declarations.
Kotlin/Native
runtime
declarations
Take a look at Kotlin runtime declarations:
NS_ASSUME_NONNULL_BEGIN
__attribute__((objc_runtime_name("KotlinMutableSet")))
__attribute__((swift_name("KotlinMutableSet")))
@interface DemoMutableSet<ObjectType> : NSMutableSet<ObjectType>
@end;
__attribute__((objc_runtime_name("KotlinMutableDictionary")))
__attribute__((swift_name("KotlinMutableDictionary")))
@interface DemoMutableDictionary<KeyType, ObjectType> : NSMutableDictionary<KeyType, ObjectType>
@end;
Kotlin classes have a KotlinBase base class in Objective-C, the class extends the NSObject class there. There are also
have wrappers for collections and exceptions. Most of the collection types are mapped to similar collection types from the
other side:
745
Kotlin Swift Objective-C
Kotlin
numbers
and
NSNumber
The next part of the <Framework>/Headers/Demo.h contains number type mappings between Kotlin/Native and
NSNumber. There is the base class called DemoNumber in Objective-C and KotlinNumber in Swift. It extends NSNumber.
There are also child classes per Kotlin number type:
- KotlinNumber <Package>Number -
746
Every number type has a class method to create a new instance from the related simple type. Also, there is an instance
method to extract a simple value back. Schematically, declarations look like that:
__attribute__((objc_runtime_name("Kotlin__TYPE__")))
__attribute__((swift_name("Kotlin__TYPE__")))
@interface Demo__TYPE__ : DemoNumber
- (instancetype)initWith__TYPE__:(__CTYPE__)value;
+ (instancetype)numberWith__TYPE__:(__CTYPE__)value;
@end;
Where __TYPE__ is one of the simple type names and __CTYPE__ is the related Objective-C type, for example,
initWithChar(char).
These types are used to map boxed Kotlin number types into Objective-C and Swift. In Swift, you may simply call the
constructor to create an instance, for example, KotlinLong(value: 42).
Classes
and
objects
from
Kotlin
Let's see how class and object are mapped to Objective-C and Swift. The generated <Framework>/Headers/Demo.h file
contains the exact definitions for Class, Interface, and Object:
NS_ASSUME_NONNULL_BEGIN
__attribute__((objc_subclassing_restricted))
__attribute__((swift_name("Object")))
@interface DemoObject : KotlinBase
+ (instancetype)alloc __attribute__((unavailable));
+ (instancetype)allocWithZone:(struct _NSZone *)zone __attribute__((unavailable));
+ (instancetype)object __attribute__((swift_name("init()")));
@property (readonly) NSString *field;
@end;
__attribute__((swift_name("Interface")))
@protocol DemoInterface
@required
- (void)iMember __attribute__((swift_name("iMember()")));
@end;
__attribute__((objc_subclassing_restricted))
__attribute__((swift_name("Clazz")))
@interface DemoClazz : KotlinBase <DemoInterface>
- (instancetype)init __attribute__((swift_name("init()")))
__attribute__((objc_designated_initializer));
+ (instancetype)new __attribute__((availability(swift, unavailable, message="use object
initializers instead")));
- (DemoLong * _Nullable)memberP:(int32_t)p __attribute__((swift_name("member(p:)")));
@end;
The code is full of Objective-C attributes, which are intended to help the use of the framework from both Objective-C and
Swift languages. DemoClazz, DemoInterface, and DemoObject are created for Clazz, Interface, and Object respectively.
The Interface is turned into @protocol, both a class and an object are represented as @interface. The Demo prefix comes
from the -output parameter of the kotlinc-native compiler and the framework name. You can see here that the nullable
return type ULong? is turned into DemoLong* in Objective-C.
747
Global
declarations
from
Kotlin
All global functions from Kotlin are turned into DemoLibKt in Objective-C and into LibKt in Swift, where Demo is the
framework name and set by the -output parameter of kotlinc-native.
NS_ASSUME_NONNULL_BEGIN
__attribute__((objc_subclassing_restricted))
__attribute__((swift_name("LibKt")))
@interface DemoLibKt : KotlinBase
+ (void)forIntegersB:(int8_t)b s:(int16_t)s i:(int32_t)i l:(DemoLong * _Nullable)l
__attribute__((swift_name("forIntegers(b:s:i:l:)")));
+ (void)forFloatsF:(float)f d:(DemoDouble * _Nullable)d
__attribute__((swift_name("forFloats(f:d:)")));
+ (NSString *)stringsStr:(NSString * _Nullable)str __attribute__((swift_name("strings(str:)")));
+ (NSString * _Nullable)acceptFunF:(NSString * _Nullable (^)(NSString *))f
__attribute__((swift_name("acceptFun(f:)")));
+ (NSString * _Nullable (^)(NSString *))supplyFun __attribute__((swift_name("supplyFun()")));
@end;
You see that Kotlin String and Objective-C NSString* are mapped transparently. Similarly, Unit type from Kotlin is
mapped to void. We see primitive types are mapped directly. Non-nullable primitive types are mapped transparently.
Nullable primitive types are mapped into Kotlin<TYPE>* types, as shown in the table above. Both higher order functions
acceptFunF and supplyFun are included, and accept Objective-C blocks.
More information about all other types mapping details can be found in the Objective-C Interop documentation article
Garbage
collection
and
reference
counting
Objective-C and Swift use reference counting. Kotlin/Native has its own garbage collection too. Kotlin/Native garbage
collection is integrated with Objective-C/Swift reference counting. You do not need to use anything special to control the
lifetime of Kotlin/Native instances from Swift or Objective-C.
Use
the
code
from
Objective-C
Let's call the framework from Objective-C. For that, create the main.m file with the following content:
#import <Foundation/Foundation.h>
#import <Demo/Demo.h>
748
[DemoLibKt forFloatsF:2.71 d:nil];
NSString* ret = [DemoLibKt acceptFunF:^NSString * _Nullable(NSString * it) {
return [it stringByAppendingString:@" Kotlin is fun"];
}];
NSLog(@"%@", ret);
return 0;
}
}
Here you call Kotlin classes directly from Objective-C code. A Kotlin object has the class method function object, which
allows us to get the only instance of the object and to call Object methods on it. The widespread pattern is used to create
an instance of the Clazz class. You call the [[ DemoClazz alloc] init] on Objective-C. You may also use [DemoClazz new]
for constructors without parameters. Global declarations from the Kotlin sources are scoped under the DemoLibKt class
in Objective-C. All methods are turned into class methods of that class. The strings function is turned into
DemoLibKt.stringsStr function in Objective-C, you can pass NSString directly to it. The return is visible as NSString too.
Use
the
code
from
Swift
The framework that you compiled with Kotlin/Native has helper attributes to make it easier to use with Swift. Convert the
previous Objective-C example into Swift. As a result, you'll have the following code in main.swift:
import Foundation
import Demo
LibKt.forIntegers(b: 1, s: 2, i: 3, l: 4)
LibKt.forFloats(f: 2.71, d: nil)
The Kotlin code is turned into very similar looking code in Swift. There are some small differences, though. In Kotlin any
object has only one instance. Kotlin object Object now has a constructor in Swift, and we use the Object() syntax to
access the only instance of it. The instance is always the same in Swift, so that Object() === Object() is true. Methods and
property names are translated as-is. Kotlin String is turned into Swift String too. Swift hides NSNumber* boxing from us
too. We can pass a Swift closure to Kotlin and call a Kotlin lambda function from Swift too.
More documentation on the types mapping can be found in the Objective-C Interop article.
749
Xcode
and
framework
dependencies
You need to configure an Xcode project to use our framework. The configuration depends on the target platform.
Xcode
for
macOS
target
First, in the General tab of the target configuration, under the Linked Frameworks and Libraries section, you need to
include our framework. This will make Xcode look at our framework and resolve imports both from Objective-C and Swift.
The second step is to configure the framework search path of the produced binary. It is also known as rpath or run-time
search path. The binary uses the path to look for the required frameworks. We do not recommend installing additional
frameworks to the OS if it is not needed. You should understand the layout of your future application, for example, you
may have the Frameworks folder under the application bundle with all the frameworks you use. The @rpath parameter can
be configured in Xcode. You need to open the project configuration and find the Runpath Search Paths section. Here you
specify the relative path to the compiled framework.
Xcode
for
iOS
targets
First, you need to include the compiled framework in the Xcode project. To do this, add the framework to the Frameworks,
Libraries, and Embedded Content section of the General tab of the target configuration page.
The second step is to then include the framework path into the Framework Search Paths section of the Build Settings tab
of the target configuration page. It is possible to use the $(PROJECT_DIR) macro to simplify the setup.
The iOS simulator requires a framework compiled for the ios_x64 target, the iOS_sim folder in our case.
This Stackoverflow thread contains a few more recommendations. Also, the CocoaPods package manager may be helpful
to automate the process too.
Next
steps
Kotlin/Native has bidirectional interop with Objective-C and Swift languages. Kotlin objects integrate with Objective-
C/Swift reference counting. Unused Kotlin objects are automatically removed. The Objective-C Interop article contains
more information on the interop implementation details. Of course, it is possible to import an existing framework and use
it from Kotlin. Kotlin/Native comes with a good set of pre-imported system frameworks.
Kotlin/Native supports C interop too. Check out the Kotlin/Native as a Dynamic Library tutorial for that.
Debugging
Kotlin/Native
Currently, the Kotlin/Native compiler produces debug info compatible with the DWARF 2 specification, so modern
debugger tools can perform the following operations:
breakpoints
750
stepping
variable inspection
Supporting the DWARF 2 specification means that the debugger tool recognizes Kotlin as C89, because before
the DWARF 5 specification, there is no identifier for the Kotlin language type in specification.
Produce
binaries
with
debug
info
with
Kotlin/Native
compiler
To produce binaries with the Kotlin/Native compiler, use the -g option on the command line.
Breakpoints
Modern debuggers provide several ways to set a breakpoint, see below for a tool-by-tool breakdown:
751
lldb
by name
(lldb) b -n kfun:main(kotlin.Array<kotlin.String>)
Breakpoint 4: where = terminator.kexe`kfun:main(kotlin.Array<kotlin.String>) + 4 at
hello.kt:2, address = 0x00000001000012e4
(lldb) b -f hello.kt -l 1
Breakpoint 1: where = terminator.kexe`kfun:main(kotlin.Array<kotlin.String>) + 4 at
hello.kt:2, address = 0x00000001000012e4
by address
(lldb) b -a 0x00000001000012e4
Breakpoint 2: address = 0x00000001000012e4
by regex, you might find it useful for debugging generated artifacts, like lambda etc. (where used # symbol in name).
gdb
by regex
(gdb) b kfun:main(kotlin.Array<kotlin.String>)
No source file named kfun.
Make breakpoint pending on future shared library load? (y or [n]) y
Breakpoint 1 (kfun:main(kotlin.Array<kotlin.String>)) pending
by location
(gdb) b hello.kt:1
752
Breakpoint 2 at 0x100001704: file /Users/minamoto/ws/.git-trees/hello.kt, line 1.
by address
(gdb) b *0x100001704
Note: breakpoint 2 also set at pc 0x100001704.
Breakpoint 3 at 0x100001704: file /Users/minamoto/ws/.git-trees/hello.kt, line 2.
Stepping
Stepping functions works mostly the same way as for C/C++ programs.
Variable
inspection
Variable inspections for var variables works out of the box for primitive types. For non-primitive types there are custom
pretty printers for lldb in konan_lldb.py:
λ cat main.kt | nl
1 fun main(args: Array<String>) {
2 var x = 1
3 var y = 2
4 var p = Point(x, y)
5 println("p = $p")
6 }
7 data class Point(val x: Int, val y: Int)
753
(int) x = 1
(int) y = 2
(ObjHeader *) p = [x: ..., y: ...]
(lldb) p p
(ObjHeader *) $2 = [x: ..., y: ...]
(lldb) script lldb.frame.FindVariable("p").GetChildMemberWithName("x").Dereference().GetValue()
'1'
(lldb)
Getting representation of the object variable (var) could also be done using the built-in runtime function
Konan_DebugPrint (this approach also works for gdb, using a module of command syntax):
Known
issues
performance of Python bindings.
754
Symbolicating
iOS
crash
reports
Debugging an iOS application crash sometimes involves analyzing crash reports. More info about crash reports can be
found in the Apple documentation.
Crash reports generally require symbolication to become properly readable: symbolication turns machine code addresses
into human-readable source locations. The document below describes some specific details of symbolicating crash
reports from iOS applications using Kotlin.
Producing
.dSYM
for
release
Kotlin
binaries
To symbolicate addresses in Kotlin code (e.g. for stack trace elements corresponding to Kotlin code) .dSYM bundle for
Kotlin code is required.
By default, Kotlin/Native compiler produces .dSYM for release (i.e. optimized) binaries on Darwin platforms. This can be
disabled with -Xadd-light-debug=disable compiler flag. At the same time, this option is disabled by default for other
platforms. To enable it, use the -Xadd-light-debug=enable compiler option.
Kotlin
kotlin {
targets.withType<org.jetbrains.kotlin.gradle.plugin.mpp.KotlinNativeTarget> {
binaries.all {
freeCompilerArgs += "-Xadd-light-debug={enable|disable}"
}
}
}
Groovy
kotlin {
targets.withType(org.jetbrains.kotlin.gradle.plugin.mpp.KotlinNativeTarget) {
binaries.all {
freeCompilerArgs += "-Xadd-light-debug={enable|disable}"
}
}
}
In projects created from IntelliJ IDEA or AppCode templates these .dSYM bundles are then discovered by Xcode
automatically.
Make
frameworks
static
when
using
rebuild
from
bitcode
Rebuilding Kotlin-produced framework from bitcode invalidates the original .dSYM. If it is performed locally, make sure
the updated .dSYM is used when symbolicating crash reports.
755
If rebuilding is performed on App Store side, then .dSYM of rebuilt dynamic framework seems discarded and not
downloadable from App Store Connect. In this case, it may be required to make the framework static.
Kotlin
kotlin {
targets.withType<org.jetbrains.kotlin.gradle.plugin.mpp.KotlinNativeTarget> {
binaries.withType<org.jetbrains.kotlin.gradle.plugin.mpp.Framework> {
isStatic = true
}
}
}
Groovy
kotlin {
targets.withType(org.jetbrains.kotlin.gradle.plugin.mpp.KotlinNativeTarget) {
binaries.withType(org.jetbrains.kotlin.gradle.plugin.mpp.Framework) {
isStatic = true
}
}
}
Decode
inlined
stack
frames
Xcode doesn't seem to properly decode stack trace elements of inlined function calls (these aren't only Kotlin inline
functions but also functions that are inlined when optimizing machine code). So some stack trace elements may be
missing. If this is the case, consider using lldb to process crash report that is already symbolicated by Xcode, for
example:
This command should output crash report that is additionally processed and includes inlined stack trace elements.
Tips
for
improving
Kotlin/Native
compilation
times
The Kotlin/Native compiler is constantly receiving updates that improve its performance. With the latest Kotlin/Native
compiler and a properly configured build environment, you can significantly improve the compilation times of your
projects with Kotlin/Native targets.
756
Read on for our tips on how to speed up the Kotlin/Native compilation process.
General
recommendations
Use the most recent version of Kotlin. This way you will always have the latest performance improvements.
Avoid creating huge classes. They take a long time to compile and load during execution.
Preserve downloaded and cached components between builds. When compiling projects, Kotlin/Native downloads the
required components and caches some results of its work to the $USER_HOME/.konan directory. The compiler uses
this directory for subsequent compilations, making them take less time to complete.
When building in containers (such as Docker) or with continuous integration systems, the compiler may have to create
the ~/.konan directory from scratch for each build. To avoid this step, configure your environment to preserve ~/.konan
between builds. For example, redefine its location using the KONAN_DATA_DIR environment variable.
Gradle
configuration
The first compilation with Gradle usually takes more time than subsequent ones due to the need to download the
dependencies, build caches, and perform additional steps. You should build your project at least twice to get an accurate
reading of the actual compilation times.
Here are some recommendations for configuring Gradle for better compilation performance:
Increase the Gradle heap size. Add org.gradle.jvmargs=-Xmx3g to gradle.properties. If you use parallel builds, you
might need to make the heap even larger or choose the right number of threads with org.gradle.parallel.threads.
Build only the binaries you need. Don't run Gradle tasks that build the whole project, such as build or assemble, unless
you really need to. These tasks build the same code more than once, increasing the compilation times. In typical cases
such as running tests from IntelliJ IDEA or starting the app from Xcode, the Kotlin tooling avoids executing
unnecessary tasks.
If you have a non-typical case or build configuration, you might need to choose the task yourself.
linkDebug*: To run your code during development, you usually need only one binary, so running the corresponding
linkDebug* task should be enough. Keep in mind that compiling a release binary (linkRelease*) takes more time than
compiling a debug one.
packForXcode: Since iOS simulators and devices have different processor architectures, it's a common approach
to distribute a Kotlin/Native binary as a universal (fat) framework. During local development, it will be faster to build
the .framework for only the platform you’re using.
To build a platform-specific framework, call the packForXcode task generated by the KMM project wizard.
757
Remember that in this case, you will need to clean the build using ./gradlew clean after switching
between the device and the simulator. See this issue for details.
Don’t disable the Gradle daemon without having a good reason to. Kotlin/Native runs from the Gradle daemon by
default. When it’s enabled, the same JVM process is used and there is no need to warm it up for each compilation.
Local build cache: Add org.gradle.caching=true to your gradle.properties or run with --build-cache on the command
line.
Remote build cache in continuous integration environments. Learn how to configure the remote build cache.
Use the compiler caches. Starting from 1.5.0-M1, linuxX64 and iosArm64 targets have experimental opt-in support for
compiler caches. They improve compilation times for debug builds (for linuxX64, this feature is only available on Linux
hosts). To enable the compiler caches, add kotlin.native.cacheKind.linuxX64=static or
kotlin.native.cacheKind.iosArm64=static to gradle.properties.
The following targets already have the compiler caches enabled by default:
iosX64
iosSimulatorArm64
macosX64
macosArm64
Enable previously disabled features of Kotlin/Native. There are properties that disable the Gradle daemon and
compiler caches – kotlin.native.disableCompilerDaemon=true and kotlin.native.cacheKind=none. If you had issues
with these features before and added these lines to your gradle.properties or Gradle arguments, remove them and
check whether the build completes successfully. It is possible that these properties were added previously to work
around issues that have already been fixed.
Kotlin/Native
FAQ
How
do
I
run
my
program?
Define a top-level function fun main(args: Array<String>) or just fun main() if you are not interested in passed arguments,
please ensure it's not in a package. Also compiler switch -entry could be used to make any function taking Array<String>
or no arguments and return Unit as an entry point.
What
is
Kotlin/Native
memory
management
model?
758
Kotlin/Native provides an automated memory management scheme, similar to what Java or Swift provides. The current
implementation includes an automated reference counter with a cycle collector to collect cyclical garbage.
How
do
I
create
a
shared
library?
Use the -produce dynamic compiler switch, or binaries.sharedLib() in Gradle.
kotlin {
iosArm64("mylib") {
binaries.sharedLib()
}
}
It will produce a platform-specific shared object (.so on Linux, .dylib on macOS, and .dll on Windows targets) and a C
language header, allowing the use of all public APIs available in your Kotlin/Native program from C/C++ code. See this
example of using such a shared object to provide a bridge between Python and Kotlin/Native.
How
do
I
create
a
static
library
or
an
object
file?
Use the -produce static compiler switch, or binaries.staticLib() in Gradle.
kotlin {
iosArm64("mylib") {
binaries.staticLib()
}
}
It will produce a platform-specific static object (.a library format) and a C language header, allowing you to use all the
public APIs available in your Kotlin/Native program from C/C++ code.
How
do
I
run
Kotlin/Native
behind
a
corporate
proxy?
As Kotlin/Native needs to download a platform specific toolchain, you need to specify -Dhttp.proxyHost=xxx -
Dhttp.proxyPort=xxx as the compiler's or gradlew arguments, or set it via the JAVA_OPTS environment variable.
How
do
I
specify
a
custom
Objective-C
prefix/name
for
my
Kotlin
framework?
Use the -module-name compiler option or matching Gradle DSL statement.
Kotlin
759
kotlin {
iosArm64("myapp") {
binaries.framework {
freeCompilerArgs += listOf("-module-name", "TheName")
}
}
}
Groovy
kotlin {
iosArm64("myapp") {
binaries.framework {
freeCompilerArgs += ["-module-name", "TheName"]
}
}
}
How
do
I
rename
the
iOS
framework?
The default name is for an iOS framework is <project name>.framework. To set a custom name, use the baseName
option. This will also set the module name.
kotlin {
iosArm64("myapp") {
binaries {
framework {
baseName = "TheName"
}
}
}
}
How
do
I
enable
bitcode
for
my
Kotlin
framework?
By default gradle plugin adds it on iOS target.
kotlin {
iosArm64("myapp") {
binaries {
760
framework {
// Use "marker" to embed the bitcode marker (for debug builds).
// Use "disable" to disable embedding.
embedBitcode("bitcode") // for release binaries.
}
}
}
}
These options have nearly the same effect as clang's -fembed-bitcode/ -fembed-bitcode-marker and swiftc's -embed-
bitcode/ -embed-bitcode-marker.
Why
do
I
see
InvalidMutabilityException?
It likely happens, because you are trying to mutate a frozen object. An object can transfer to the frozen state either
explicitly, as objects reachable from objects on which the kotlin.native.concurrent.freeze is called, or implicitly (i.e.
reachable from enum or global singleton object - see the next question).
How
do
I
make
a
singleton
object
mutable?
Currently, singleton objects are immutable (i.e. frozen after creation), and it's generally considered good practise to have
the global state immutable. If for some reason you need a mutable state inside such an object, use the
@konan.ThreadLocal annotation on the object. Also the kotlin.native.concurrent.AtomicReference class could be used to
store different pointers to frozen objects in a frozen object and automatically update them.
How
can
I
compile
my
project
with
unreleased
versions
of
Kotlin/Native?
First, please consider trying preview versions.
In case you need an even more recent development version, you can build Kotlin/Native from source code: clone Kotlin
repository and follow these steps.
Kotlin
releases
We ship different types of releases:
Incremental releases (1. x. y) that are shipped between feature releases and include updates in the tooling,
performance improvements, and bug fixes.
Bug fix releases (1. x. yz) that include bug fixes for incremental releases.
761
For example, for the feature release 1.3 we had several incremental releases including 1.3.10, 1.3.20, and 1.3.70. For
1.3.70, we had 2 bug fix releases – 1.3.71 and 1.3.72.
For each incremental and feature release, we also ship several preview ( EAP) versions for you to try new features before
they are released. See Early Access Preview for details.
Update
to
a
new
release
IntelliJ IDEA and Android Studio suggest updating to a new release once it is out. When you accept the suggestion, it
automatically updates the Kotlin plugin to the new version. You can check the Kotlin version in Tools | Kotlin | Configure
Kotlin Plugin Updates.
If you have projects created with earlier Kotlin versions, change the Kotlin version in your projects and update kotlinx
libraries if necessary – check the recommended versions.
If you are migrating to the new feature release, Kotlin plugin's migration tools will help you with the migration.
IDE
support
The IDE support for the latest version of the language is available for the following versions of IntelliJ IDEA and Android
Studio:
IntelliJ IDEA:
Latest stable (IntelliJ IDEA 2021.2 version)
Android Studio:
Latest released version
Release
details
The following table lists details of latest Kotlin releases.
762
Build info Build highlights Recommended kotlinx library versions
1.5.31 A bug fix release for Kotlin 1.5.30. kotlinx.serialization version: 1.3.0-RC
Released:
September Learn more about Kotlin 1.5.30. kotlinx.coroutines version: 1.5.2
20, 2021
kotlinx.atomicfu version: 0.16.3
Release on
ktor version: 1.6.3
GitHub
kotlinx.html version: 0.7.2
1.5.30 An incremental release with various improvements such kotlinx.serialization version: 1.3.0-RC
Released: as:
kotlinx.coroutines version: 1.5.1
August 23,
2021 Instantiation of annotation classes on JVM
kotlinx.atomicfu version: 0.16.2
763
Build info Build highlights Recommended kotlinx library versions
1.5.21 A bug fix release for Kotlin 1.5.20. kotlinx.serialization version: 1.2.1
Released:
July 13, Learn more about Kotlin 1.5.20. kotlinx.coroutines version: 1.5.0
2021
kotlinx.atomicfu version: 0.16.1
Release on
ktor version: 1.6.0
GitHub
kotlinx.html version: 0.7.2
1.5.20 An incremental release with various improvements such kotlinx.serialization version: 1.2.1
Released: as:
June 24, kotlinx.coroutines version: 1.5.0
764
Build info Build highlights Recommended kotlinx library versions
1.5.10 A bug fix release for Kotlin 1.5.0. kotlinx.serialization version: 1.2.1
Released:
May 24, Learn more about Kotlin 1.5.0. kotlinx.coroutines version: 1.5.0
2021
kotlinx.atomicfu version: 0.16.1
Release on
ktor version: 1.5.4
GitHub
1.5.0 A feature release with new language features, kotlinx.serialization version: 1.2.1
Released: performance improvements, and evolutionary changes
May 5, kotlinx.coroutines version: 1.5.0-RC
such as stabilizing experimental APIs.
2021
kotlinx.atomicfu version: 0.16.1
Learn more in:
Release on
ktor version: 1.5.3
Release blog post
GitHub
kotlinx.html version: 0.7.2
What's new in Kotlin 1.5.0
765
Build info Build highlights Recommended kotlinx library versions
1.4.32 A bug fix release for Kotlin 1.4.30. kotlinx.serialization version: 1.1.0
Released:
March 22, Learn more about Kotlin 1.4.30. kotlinx.coroutines version: 1.4.3
2021
kotlinx.atomicfu version: 0.15.2
Release on
ktor version: 1.5.2
GitHub
kotlinx.html version: 0.7.2
1.4.31 A bug fix release for Kotlin 1.4.30 kotlinx.serialization version: 1.1.0
Released:
February Learn more about Kotlin 1.4.30. kotlinx.coroutines version: 1.4.2
25, 2021
kotlinx.atomicfu version: 0.15.1
Release on
ktor version: 1.5.1
GitHub
766
Build info Build highlights Recommended kotlinx library versions
1.4.30 An incremental release with various improvements such kotlinx.serialization version: 1.1.0-RC
Released: as:
kotlinx.coroutines version: 1.4.2
February 3,
2021 New JVM backend, now in Beta
kotlinx.atomicfu version: 0.15.1
Release on
Preview of new language features
ktor version: 1.5.1
GitHub
Improved Kotlin/Native performance
kotlinx.html version: 0.7.2
Standard library API improvements
kotlinx-nodejs version: 0.0.7
Learn more in:
The versions of libraries from kotlin-wrappers
Release blog post (such as kotlin-react) can be found in the
corresponding repository.
What's new in Kotlin 1.4.30
1.4.21 A bug fix release for Kotlin 1.4.20 kotlinx.serialization version: 1.0.1
Released:
December Learn more about Kotlin 1.4.20. kotlinx.coroutines version: 1.4.1
7, 2020
kotlinx.atomicfu version: 0.14.4
Release on
ktor version: 1.4.1
GitHub
kotlinx.html version: 0.7.2
767
Build info Build highlights Recommended kotlinx library versions
1.4.20 An incremental release with various improvements such kotlinx.serialization version: 1.0.1
Released: as:
kotlinx.coroutines version: 1.4.1
November
23, 2020 Supporting new JVM features, like string
kotlinx.atomicfu version: 0.14.4
concatenation via invokedynamic
Release on
ktor version: 1.4.1
GitHub
Improved performance and exception handling for
KMM projects kotlinx.html version: 0.7.2
1.4.10 A bug fix release for Kotlin 1.4.0. kotlinx.serialization version: 1.0.0-RC
Released:
September Learn more about Kotlin 1.4.0. kotlinx.coroutines version: 1.3.9
7, 2020
kotlinx.atomicfu version: 0.14.4
Release on
ktor version: 1.4.0
GitHub
kotlinx.html version: 0.7.2
768
Build info Build highlights Recommended kotlinx library versions
1.4.0 A feature release with many features and improvements kotlinx.serialization version: 1.0.0-RC
1.3.72 A bug fix release for Kotlin 1.3.70. kotlinx.serialization version: 0.20.0
Released:
April 15, Learn more about Kotlin 1.3.70. kotlinx.coroutines version: 1.3.8
2020
kotlinx.atomicfu version: 0.14.2
Release on
ktor version: 1.3.2
GitHub
kotlinx.html version: 0.7.1
On the JVM, you usually can use library versions other than the recommended ones.
KMM
plugin
releases
Since KMM is now in Alpha, we are working on stabilizing the KMM plugin for Android Studio and will be regularly
releasing new versions that include new features, improvements, and bug fixes.
Ensure that you have the latest version of the KMM plugin!
769
Update
to
the
new
release
Android Studio will suggest updating to a new KMM plugin release as soon as it is available. If you accept the suggestion,
it will automatically update the KMM plugin to the latest version. You’ll need to restart Android Studio to complete the
plugin installation.
You can check the KMM plugin version and update the plugin manually in Preferences | Plugins.
You need a compatible version of Kotlin for the KMM plugin to work correctly. You can find compatible versions in the
release details. You can check your Kotlin version and update it in Preferences | Plugins or in Tools | Kotlin | Configure
Plugin Updates.
If you do not have a compatible version of Kotlin installed, the KMM plugin will be disabled. You will need to
update your Kotlin version, and then enable the KMM plugin in Preferences | Plugins.
Release
details
The following table lists the details of the latest KMM plugin releases:
Added error notification after a project with CocoaPods was generated, but the
CocoaPods gem has not been installed.
Added support Apple M1 simulator target in generated shared module with Kotlin
1.5.30.
Released: June 10, Support for Kotlin 1.5.20: using the new framework-packing task for
2021 Kotlin/Native in the Project Wizard.
770
Release info Release highlights Compatible Kotlin
version
0.2.5 Fixed compatibility with Android Studio Arctic Fox 2020.3.1 Beta 1 and higher. Kotlin 1.5.10
0.2.4 Use this version of the plugin with Android Studio 4.2 or Android Studio Kotlin 1.5.0
2020.3.1 Canary 8 or higher.
Released: May 5,
2021 Compatibility with Kotlin 1.5.0.
Ability to use the CocoaPods dependency manager in the New KMM Module
Wizard for iOS integration.
Released: April 5, Ability to use the CocoaPods dependency manager in the Project Wizard for iOS
2021 integration.
Sample tests are no longer generated if "Add sample tests for Shared Module" is
unchecked.
Released: March 3, Ability to set up a location for the Xcode project file in the iOS run configuration.
2021
Support for Android Studio 2020.3.1 Canary 8.
0.2.1 Use this version of the plugin with Android Studio 4.2. Kotlin 1.4.30
771
Release info Release highlights Compatible Kotlin
version
Released: November Support for custom scheme names that are configured in Xcode.
23, 2020
Ability to add custom build steps for the iOS run configuration.
Removed support for the Kotlin Android Extensions plugin, which is deprecated
in Kotlin 1.4.20.
Fixed saving physical device configuration after disconnecting from the host.
0.1.3 Added compatibility with iOS 14 and Xcode 12. Kotlin 1.4.10
Released: October 2, Fixed naming in platform tests created by the KMM Wizard. Kotlin 1.4.20
2020
0.1.1 Fixed compatibility with Android Studio Canary 8 and higher. Kotlin 1.4.10
0.1.0 The first version of the KMM plugin. Learn more in the blog post. Kotlin 1.4.0
Kotlin
plugin
releases
772
The IntelliJ Kotlin plugin and IntelliJ IDEA are on the same release cycle. To speed up the testing and delivery of new
features, the plugin and the platform have been moved to the same codebase and ship simultaneously. Kotlin releases
happen independently according to the new release cadence.
Kotlin plugin releases introduce only IDE related features. For example, code formatting and debugging tools.
This also affects the versioning of the Kotlin plugin. Releases now have the same version as the simultaneous IntelliJ IDEA
release. You can learn more about new release cadence in this blog post.
Update
to
a
new
release
IntelliJ IDEA and Android Studio suggest updating to a new release once it is out. When you accept the suggestion, it
automatically updates the Kotlin plugin to the new version. You can check the Kotlin plugin version in Tools | Kotlin |
Configure Kotlin Plugin Updates.
If you are migrating to the new feature release, Kotlin plugin's migration tools will help you with the migration.
Release
details
The following table lists the details of the latest Kotlin plugin releases:
773
Release info Release highlights
EditorConfig support
Kotlin
roadmap
Last modified on May 2021
Welcome to the Kotlin roadmap! Get a sneak peek into the priorities of the Kotlin Team.
Key
priorities
The goal of this roadmap is to give you a big picture. Here’s a list of our key priorities – the areas we are investing
the most effort into:
New compiler: a rewrite of the Kotlin compiler optimized for speed, parallelism, and unification. Later we will also work
on pluggability.
Fast and smooth IDE: improving the stability and performance of the Kotlin IDE.
Kotlin for JVM server-side development: expanding support for server-side use cases across the Kotlin ecosystem.
Kotlin Multiplatform Mobile: improving the user experience and feature set for sharing code on mobile platforms.
Kotlin
roadmap
by
subsystem
To view the biggest projects we're working on, visit the YouTrack board or the Roadmap details table.
774
If you have any questions or feedback about the roadmap or the items on it, feel free to post them to YouTrack tickets or
in the #kotlin-roadmap channel of Kotlin Slack (request an invite).
YouTrack
board
Visit the roadmap board in our issue tracker YouTrack
Roadmap
details
775
Subsystem In focus now Postponed for later
Language 🆕 Support sealed (exhaustive) whens ⸠Support JVM sealed classes
Compiler 🆕 Release the new compiler frontend in Alpha for ⸠Stable Compiler Plugin API
core
JVM target
⸠Scripting improvements
🆕 Finalize support for jspecify
JS IR BE: Add an ability to generate separate JS files ⸠Improve Dukat support
for each module
776
Subsystem In focus now Postponed for later
Kotlin/Wasm 🆕 Implement an experimental version of Note: Wasm support in Kotlin/Native (through LLVM) will
be deprecated and removed
Kotlin/Wasm compiler backend
Kotlin/Native 🆕 Implement safe initialization for top-level ⸠Support Mac Catalyst
properties
⸠Direct interoperability with Swift
Prototype a new garbage collector
⸠Interoperability with C++
Improve compilation time
⸠Support Alpine Linux
Improve exporting Kotlin code to Objective-C
Kotlin 🆕 Support the Apple Silicon target in the Kotlin ⸠Improve Kotlin/Native debugging experience
Multiplatform
Multiplatform tooling
⸠Improve Gradle and Compiler error messages
Improve UX of using Native libraries in Kotlin
⸠Sharing code between JVM and Android
Improve dependency management for iOS
IDE Prototype IDE plugin with the new compiler frontend ⸠Advanced tooling that users have in Java but
is missing in Kotlin
Improve IDE performance
⸠Quality of less frequently used features,
Improve debugging experience
except blocking problems
Build tools Improve the performance of Gradle incremental ⸠Improvements in Kotlin Maven support
compilation
777
Subsystem In focus now Postponed for later
Libraries 🆕 Improve kotlinx-serialization (release v1.3.0) ⸠Improve usability of multi-threaded coroutines
library for Kotlin/Native
🆕 Improve kotlinx-coroutines (release v1.6.0)
⸠kotlinx-cli
🆕 Stabilize Duration API in the standard library
⸠binary-compatibility-validator
🆕 Get rid of !! for readLine() in the standard library
⸠kotlinx-io
🆕 Stabilize and document atomicfu
⸠Any new multiplatform libraries
Improve kotlinx-datetime library
This roadmap is not an exhaustive list of all things the team is working on, only the biggest projects.
It lists some things that are postponed and will NOT get the team’s attention in the nearest future.
We will adjust our priorities as we go and update the roadmap approximately every six months.
778
What's
changed
since
January
2021
Completed
items
We've completed the following items from the previous roadmap:
✅ Compiler core: Support incremental compilation for the new compiler
✅ Kotlin/JS: JS IR BE: Prototype lazy initialization for top-level properties like in JVM
✅ Multiplatform: Improve frontend and IDE import stability for Multiplatform projects
✅ IDE: Improve cross-language support in the Inline Method and Change Signature refactorings
Postponed
items
We've decided to postpone the following items from the previous roadmap:
779
Other postponed items remain in this state from earlier roadmap versions.
New
items
We've added the following items to the roadmap:
🆕 Language: Allow repeating annotations with runtime retention when compiling under Java 8
🆕 Language: Improve type inference in corner cases for popular Java APIs
🆕 Compiler core: Release the new compiler frontend in Alpha for JVM target
🆕 Multiplatform: Support the Apple Silicon target in the Kotlin Multiplatform tooling
🆕 Build tools: Improve user experience with the Kotlin Gradle plugin
780
🆕 Website: Make the UI and navigation consistent
🆕 Website: Update community graphic assets to the new Kotlin visual style
Items
in
progress
All other previously identified roadmap items are in progress. You can check their YouTrack tickets for updates.
Collections
overview
The Kotlin Standard Library provides a comprehensive set of tools for managing collections – groups of a variable
number of items (possibly zero) that share significance to the problem being solved and are operated upon commonly.
Collections are a common concept for most programming languages, so if you're familiar with, for example, Java or
Python collections, you can skip this introduction and proceed to the detailed sections.
A collection usually contains a number of objects (this number may also be zero) of the same type. Objects in a collection
are called elements or items. For example, all the students in a department form a collection that can be used to calculate
their average age.
List is an ordered collection with access to elements by indices – integer numbers that reflect their position.
Elements can occur more than once in a list. An example of a list is a telephone number: it's a group of digits, their
order is important, and they can repeat.
Set is a collection of unique elements. It reflects the mathematical abstraction of set: a group of objects without
repetitions. Generally, the order of set elements has no significance. For example, the numbers on lottery tickets form
a set: they are unique, and their order is not important.
Map (or dictionary) is a set of key-value pairs. Keys are unique, and each of them maps to exactly one value. The
values can be duplicates. Maps are useful for storing logical connections between objects, for example, an employee's
ID and their position.
Kotlin lets you manipulate collections independently of the exact type of objects stored in them. In other words, you add a
String to a list of String s the same way as you would do with Int s or a user-defined class. So, the Kotlin Standard Library
offers generic interfaces, classes, and functions for creating, populating, and managing collections of any type.
The collection interfaces and related functions are located in the kotlin.collections package. Let's get an overview of its
contents.
Collection
types
The Kotlin Standard Library provides implementations for basic collection types: sets, lists, and maps. A pair of interfaces
represent each collection type:
781
A read-only interface that provides operations for accessing collection elements.
A mutable interface that extends the corresponding read-only interface with write operations: adding, removing, and
updating its elements.
Note that altering a mutable collection doesn't require it to be a var: write operations modify the same mutable collection
object, so the reference doesn't change. Although, if you try to reassign a val collection, you'll get a compilation error.
fun main() {
//sampleStart
val numbers = mutableListOf("one", "two", "three", "four")
numbers.add("five") // this is OK
println(numbers)
//numbers = mutableListOf("six", "seven") // compilation error
//sampleEnd
The read-only collection types are covariant. This means that, if a Rectangle class inherits from Shape, you can use a
List<Rectangle> anywhere the List<Shape> is required. In other words, the collection types have the same subtyping
relationship as the element types. Maps are covariant on the value type, but not on the key type.
In turn, mutable collections aren't covariant; otherwise, this would lead to runtime failures. If MutableList<Rectangle> was
a subtype of MutableList<Shape>, you could insert other Shape inheritors (for example, Circle) into it, thus violating its
Rectangle type argument.
782
Collection interfaces hierarchy
Collection
Collection<T> is the root of the collection hierarchy. This interface represents the common behavior of a read-only
collection: retrieving size, checking item membership, and so on. Collection inherits from the Iterable<T> interface that
defines the operations for iterating elements. You can use Collection as a parameter of a function that applies to different
collection types. For more specific cases, use the Collection 's inheritors: List and Set.
783
}
fun main() {
val words = "A long time ago in a galaxy far far away".split(" ")
val shortWords = mutableListOf<String>()
words.getShortWordsTo(shortWords, 3)
println(shortWords)
}
List
List<T> stores elements in a specified order and provides indexed access to them. Indices start from zero – the index
of the first element – and go to lastIndex which is the (list.size - 1).
fun main() {
//sampleStart
val numbers = listOf("one", "two", "three", "four")
println("Number of elements: ${numbers.size}")
println("Third element: ${numbers.get(2)}")
println("Fourth element: ${numbers[3]}")
println("Index of element \"two\" ${numbers.indexOf("two")}")
//sampleEnd
}
List elements (including nulls) can duplicate: a list can contain any number of equal objects or occurrences of a single
object. Two lists are considered equal if they have the same sizes and structurally equal elements at the same positions.
fun main() {
//sampleStart
val bob = Person("Bob", 31)
val people = listOf(Person("Adam", 20), bob, bob)
val people2 = listOf(Person("Adam", 20), Person("Bob", 31), bob)
println(people == people2)
bob.age = 32
println(people == people2)
//sampleEnd
}
MutableList<T> is a List with list-specific write operations, for example, to add or remove an element at a specific
position.
784
fun main() {
//sampleStart
val numbers = mutableListOf(1, 2, 3, 4)
numbers.add(5)
numbers.removeAt(1)
numbers[0] = 0
numbers.shuffle()
println(numbers)
//sampleEnd
}
As you see, in some aspects lists are very similar to arrays. However, there is one important difference: an array's size is
defined upon initialization and is never changed; in turn, a list doesn't have a predefined size; a list's size can be changed
as a result of write operations: adding, updating, or removing elements.
In Kotlin, the default implementation of List is ArrayList which you can think of as a resizable array.
Set
Set<T> stores unique elements; their order is generally undefined. null elements are unique as well: a Set can contain only
one null. Two sets are equal if they have the same size, and for each element of a set there is an equal element in the
other set.
fun main() {
//sampleStart
val numbers = setOf(1, 2, 3, 4)
println("Number of elements: ${numbers.size}")
if (numbers.contains(1)) println("1 is in the set")
The default implementation of Set – LinkedHashSet – preserves the order of elements insertion. Hence, the functions
that rely on the order, such as first() or last(), return predictable results on such sets.
fun main() {
//sampleStart
val numbers = setOf(1, 2, 3, 4) // LinkedHashSet is the default implementation
val numbersBackwards = setOf(4, 3, 2, 1)
println(numbers.first() == numbersBackwards.first())
println(numbers.first() == numbersBackwards.last())
//sampleEnd
}
An alternative implementation – HashSet – says nothing about the elements order, so calling such functions on it
returns unpredictable results. However, HashSet requires less memory to store the same number of elements.
785
Map
Map<K, V> is not an inheritor of the Collection interface; however, it's a Kotlin collection type as well. A Map stores key-
value pairs (or entries); keys are unique, but different keys can be paired with equal values. The Map interface provides
specific functions, such as access to value by key, searching keys and values, and so on.
fun main() {
//sampleStart
val numbersMap = mapOf("key1" to 1, "key2" to 2, "key3" to 3, "key4" to 1)
println("All keys: ${numbersMap.keys}")
println("All values: ${numbersMap.values}")
if ("key2" in numbersMap) println("Value by key \"key2\": ${numbersMap["key2"]}")
if (1 in numbersMap.values) println("The value 1 is in the map")
if (numbersMap.containsValue(1)) println("The value 1 is in the map") // same as previous
//sampleEnd
}
Two maps containing the equal pairs are equal regardless of the pair order.
fun main() {
//sampleStart
val numbersMap = mapOf("key1" to 1, "key2" to 2, "key3" to 3, "key4" to 1)
val anotherMap = mapOf("key2" to 2, "key1" to 1, "key4" to 1, "key3" to 3)
println("The maps are equal: ${numbersMap == anotherMap}")
//sampleEnd
}
MutableMap is a Map with map write operations, for example, you can add a new key-value pair or update the value
associated with the given key.
fun main() {
//sampleStart
val numbersMap = mutableMapOf("one" to 1, "two" to 2)
numbersMap.put("three", 3)
numbersMap["one"] = 11
println(numbersMap)
//sampleEnd
}
The default implementation of Map – LinkedHashMap – preserves the order of elements insertion when iterating the
map. In turn, an alternative implementation – HashMap – says nothing about the elements order.
Constructing
collections
Construct
from
elements
786
The most common way to create a collection is with the standard library functions listOf<T>(), setOf<T>(),
mutableListOf<T>(), mutableSetOf<T>(). If you provide a comma-separated list of collection elements as arguments, the
compiler detects the element type automatically. When creating empty collections, specify the type explicitly.
The same is available for maps with the functions mapOf() and mutableMapOf(). The map's keys and values are passed as
Pair objects (usually created with to infix function).
Note that the to notation creates a short-living Pair object, so it's recommended that you use it only if performance isn't
critical. To avoid excessive memory usage, use alternative ways. For example, you can create a mutable map and
populate it using the write operations. The apply() function can help to keep the initialization fluent here.
Empty
collections
There are also functions for creating collections without any elements: emptyList(), emptySet(), and emptyMap(). When
creating empty collections, you should specify the type of elements that the collection will hold.
Initializer
functions
for
lists
For lists, there is a constructor that takes the list size and the initializer function that defines the element value based on
its index.
fun main() {
//sampleStart
val doubled = List(3, { it * 2 }) // or MutableList if you want to change its content later
println(doubled)
//sampleEnd
}
Concrete
type
constructors
To create a concrete type collection, such as an ArrayList or LinkedList, you can use the available constructors for these
787
types. Similar constructors are available for implementations of Set and Map.
Copy
To create a collection with the same elements as an existing collection, you can use copying functions. Collection
copying functions from the standard library create shallow copy collections with references to the same elements. Thus, a
change made to a collection element reflects in all its copies.
Collection copying functions, such as toList(), toMutableList(), toSet() and others, create a snapshot of a collection at a
specific moment. Their result is a new collection of the same elements. If you add or remove elements from the original
collection, this won't affect the copies. Copies may be changed independently of the source as well.
fun main() {
//sampleStart
val alice = Person("Alice")
val sourceList = mutableListOf(alice, Person("Bob"))
val copyList = sourceList.toList()
sourceList.add(Person("Charles"))
alice.name = "Alicia"
println("First item's name is: ${sourceList[0].name} in source and ${copyList[0].name} in
copy")
println("List size is: ${sourceList.size} in source and ${copyList.size} in copy")
//sampleEnd
}
These functions can also be used for converting collections to other types, for example, build a set from a list or vice
versa.
fun main() {
//sampleStart
val sourceList = mutableListOf(1, 2, 3)
val copySet = sourceList.toMutableSet()
copySet.add(3)
copySet.add(4)
println(copySet)
//sampleEnd
}
Alternatively, you can create new references to the same collection instance. New references are created when you
initialize a collection variable with an existing collection. So, when the collection instance is altered through a reference,
the changes are reflected in all its references.
788
fun main() {
//sampleStart
val sourceList = mutableListOf(1, 2, 3)
val referenceList = sourceList
referenceList.add(4)
println("Source size: ${sourceList.size}")
//sampleEnd
}
Collection initialization can be used for restricting mutability. For example, if you create a List reference to a MutableList,
the compiler will produce errors if you try to modify the collection through this reference.
fun main() {
//sampleStart
val sourceList = mutableListOf(1, 2, 3)
val referenceList: List<Int> = sourceList
//referenceList.add(4) //compilation error
sourceList.add(4)
println(referenceList) // shows the current state of sourceList
//sampleEnd
}
Invoke
functions
on
other
collections
Collections can be created in result of various operations on other collections. For example, filtering a list creates a new
list of elements that match the filter:
fun main() {
//sampleStart
val numbers = listOf("one", "two", "three", "four")
val longerThan3 = numbers.filter { it.length > 3 }
println(longerThan3)
//sampleEnd
}
fun main() {
//sampleStart
val numbers = setOf(1, 2, 3)
println(numbers.map { it * 3 })
println(numbers.mapIndexed { idx, value -> value * idx })
//sampleEnd
}
789
fun main() {
//sampleStart
val numbers = listOf("one", "two", "three", "four")
println(numbers.associateWith { it.length })
//sampleEnd
}
For more information about operations on collections in Kotlin, see Collection operations overview.
Iterators
For traversing collection elements, the Kotlin standard library supports the commonly used mechanism of iterators –
objects that provide access to the elements sequentially without exposing the underlying structure of the collection.
Iterators are useful when you need to process all the elements of a collection one-by-one, for example, print values or
make similar updates to them.
Iterators can be obtained for inheritors of the Iterable<T> interface, including Set and List, by calling the iterator() function.
Once you obtain an iterator, it points to the first element of a collection; calling the next() function returns this element and
moves the iterator position to the following element if it exists.
Once the iterator passes through the last element, it can no longer be used for retrieving elements; neither can it be reset
to any previous position. To iterate through the collection again, create a new iterator.
fun main() {
//sampleStart
val numbers = listOf("one", "two", "three", "four")
val numbersIterator = numbers.iterator()
while (numbersIterator.hasNext()) {
println(numbersIterator.next())
}
//sampleEnd
}
Another way to go through an Iterable collection is the well-known for loop. When using for on a collection, you obtain the
iterator implicitly. So, the following code is equivalent to the example above:
fun main() {
//sampleStart
val numbers = listOf("one", "two", "three", "four")
for (item in numbers) {
println(item)
}
//sampleEnd
}
790
Finally, there is a useful forEach() function that lets you automatically iterate a collection and execute the given code for
each element. So, the same example would look like this:
fun main() {
//sampleStart
val numbers = listOf("one", "two", "three", "four")
numbers.forEach {
println(it)
}
//sampleEnd
}
List
iterators
For lists, there is a special iterator implementation: ListIterator. It supports iterating lists in both directions: forwards and
backwards.
Backward iteration is implemented by the functions hasPrevious() and previous(). Additionally, the ListIterator provides
information about the element indices with the functions nextIndex() and previousIndex().
fun main() {
//sampleStart
val numbers = listOf("one", "two", "three", "four")
val listIterator = numbers.listIterator()
while (listIterator.hasNext()) listIterator.next()
println("Iterating backwards:")
while (listIterator.hasPrevious()) {
print("Index: ${listIterator.previousIndex()}")
println(", value: ${listIterator.previous()}")
}
//sampleEnd
}
Having the ability to iterate in both directions, means the ListIterator can still be used after it reaches the last element.
Mutable
iterators
For iterating mutable collections, there is MutableIterator that extends Iterator with the element removal function remove().
So, you can remove elements from a collection while iterating it.
fun main() {
//sampleStart
val numbers = mutableListOf("one", "two", "three", "four")
val mutableIterator = numbers.iterator()
mutableIterator.next()
791
mutableIterator.remove()
println("After removal: $numbers")
//sampleEnd
}
In addition to removing elements, the MutableListIterator can also insert and replace elements while iterating the list.
fun main() {
//sampleStart
val numbers = mutableListOf("one", "four", "four")
val mutableListIterator = numbers.listIterator()
mutableListIterator.next()
mutableListIterator.add("two")
mutableListIterator.next()
mutableListIterator.set("three")
println(numbers)
//sampleEnd
}
Ranges
and
progressions
Kotlin lets you easily create ranges of values using the rangeTo() function from the kotlin.ranges package and its operator
form ... Usually, rangeTo() is complemented by in or !in functions.
Integral type ranges (IntRange, LongRange, CharRange) have an extra feature: they can be iterated over. These ranges
are also progressions of the corresponding integral types.
fun main() {
//sampleStart
for (i in 1..4) print(i)
//sampleEnd
}
To iterate numbers in reverse order, use the downTo function instead of ...
fun main() {
//sampleStart
for (i in 4 downTo 1) print(i)
//sampleEnd
792
}
It is also possible to iterate over numbers with an arbitrary step (not necessarily 1). This is done via the step function.
fun main() {
//sampleStart
for (i in 1..8 step 2) print(i)
println()
for (i in 8 downTo 1 step 2) print(i)
//sampleEnd
}
To iterate a number range which does not include its end element, use the until function:
fun main() {
//sampleStart
for (i in 1 until 10) { // i in [1, 10), 10 is excluded
print(i)
}
//sampleEnd
}
Range
A range defines a closed interval in the mathematical sense: it is defined by its two endpoint values which are both
included in the range. Ranges are defined for comparable types: having an order, you can define whether an arbitrary
instance is in the range between two given instances.
The main operation on ranges is contains, which is usually used in the form of in and !in operators.
To create a range for your class, call the rangeTo() function on the range start value and provide the end value as an
argument. rangeTo() is often called in its operator form ...
fun main() {
//sampleStart
val versionRange = Version(1, 11)..Version(1, 30)
println(Version(0, 9) in versionRange)
println(Version(1, 20) in versionRange)
//sampleEnd
}
793
Progression
As shown in the examples above, the ranges of integral types, such as Int, Long, and Char, can be treated as arithmetic
progressions of them. In Kotlin, these progressions are defined by special types: IntProgression, LongProgression, and
CharProgression.
Progressions have three essential properties: the first element, the last element, and a non-zero step. The first element is
first, subsequent elements are the previous element plus a step. Iteration over a progression with a positive step is
equivalent to an indexed for loop in Java/JavaScript.
When you create a progression implicitly by iterating a range, this progression's first and last elements are the range's
endpoints, and the step is 1.
fun main() {
//sampleStart
for (i in 1..10) print(i)
//sampleEnd
}
fun main() {
//sampleStart
for (i in 1..8 step 2) print(i)
//sampleEnd
}
For a positive step: the maximum value not greater than the end value such that (last - first) % step == 0.
For a negative step: the minimum value not less than the end value such that (last - first) % step == 0.
Thus, the last element is not always the same as the specified end value.
fun main() {
//sampleStart
for (i in 1..9 step 3) print(i) // the last element is 7
//sampleEnd
}
794
To create a progression for iterating in reverse order, use downTo instead of .. when defining the range for it.
fun main() {
//sampleStart
for (i in 4 downTo 1) print(i)
//sampleEnd
}
If you already have a progression, you can iterate it in reverse order with the reversed function:
fun main() {
//sampleStart
for (i in (1..4).reversed()) print(i)
//sampleEnd
}
Progressions implement Iterable<N>, where N is Int, Long, or Char respectively, so you can use them in various collection
functions like map, filter, and other.
fun main() {
//sampleStart
println((1..10).filter { it % 2 == 0 })
//sampleEnd
}
Sequences
Along with collections, the Kotlin standard library contains another container type – sequences (Sequence<T>).
Sequences offer the same functions as Iterable but implement another approach to multi-step collection processing.
When the processing of an Iterable includes multiple steps, they are executed eagerly: each processing step completes
and returns its result – an intermediate collection. The following step executes on this collection. In turn, multi-step
processing of sequences is executed lazily when possible: actual computing happens only when the result of the whole
processing chain is requested.
The order of operations execution is different as well: Sequence performs all the processing steps one-by-one for every
single element. In turn, Iterable completes each step for the whole collection and then proceeds to the next step.
So, the sequences let you avoid building results of intermediate steps, therefore improving the performance of the whole
collection processing chain. However, the lazy nature of sequences adds some overhead which may be significant when
processing smaller collections or doing simpler computations. Hence, you should consider both Sequence and Iterable
and decide which one is better for your case.
795
Construct
From
elements
To create a sequence, call the sequenceOf() function listing the elements as its arguments.
From
an
Iterable
If you already have an Iterable object (such as a List or a Set), you can create a sequence from it by calling asSequence().
From
a
function
One more way to create a sequence is by building it with a function that calculates its elements. To build a sequence
based on a function, call generateSequence() with this function as an argument. Optionally, you can specify the first
element as an explicit value or a result of a function call. The sequence generation stops when the provided function
returns null. So, the sequence in the example below is infinite.
fun main() {
//sampleStart
val oddNumbers = generateSequence(1) { it + 2 } // `it` is the previous element
println(oddNumbers.take(5).toList())
//println(oddNumbers.count()) // error: the sequence is infinite
//sampleEnd
}
To create a finite sequence with generateSequence(), provide a function that returns null after the last element you need.
fun main() {
//sampleStart
val oddNumbersLessThan10 = generateSequence(1) { if (it < 8) it + 2 else null }
println(oddNumbersLessThan10.count())
//sampleEnd
}
From
chunks
Finally, there is a function that lets you produce sequence elements one by one or by chunks of arbitrary sizes – the
sequence() function. This function takes a lambda expression containing calls of yield() and yieldAll() functions. They
796
return an element to the sequence consumer and suspend the execution of sequence() until the next element is requested
by the consumer. yield() takes a single element as an argument; yieldAll() can take an Iterable object, an Iterator, or
another Sequence. A Sequence argument of yieldAll() can be infinite. However, such a call must be the last: all
subsequent calls will never be executed.
fun main() {
//sampleStart
val oddNumbers = sequence {
yield(1)
yieldAll(listOf(3, 5))
yieldAll(generateSequence(7) { it + 2 })
}
println(oddNumbers.take(5).toList())
//sampleEnd
}
Sequence
operations
The sequence operations can be classified into the following groups regarding their state requirements:
Stateless operations require no state and process each element independently, for example, map() or filter(). Stateless
operations can also require a small constant amount of state to process an element, for example, take() or drop().
Stateful operations require a significant amount of state, usually proportional to the number of elements in a sequence.
If a sequence operation returns another sequence, which is produced lazily, it's called intermediate. Otherwise, the
operation is terminal. Examples of terminal operations are toList() or sum(). Sequence elements can be retrieved only with
terminal operations.
Sequences can be iterated multiple times; however some sequence implementations might constrain themselves to be
iterated only once. That is mentioned specifically in their documentation.
Sequence
processing
example
Let's take a look at the difference between Iterable and Sequence with an example.
Iterable
Assume that you have a list of words. The code below filters the words longer than three characters and prints the lengths
of first four such words.
fun main() {
//sampleStart
val words = "The quick brown fox jumps over the lazy dog".split(" ")
val lengthsList = words.filter { println("filter: $it"); it.length > 3 }
.map { println("length: ${it.length}"); it.length }
797
.take(4)
When you run this code, you'll see that the filter() and map() functions are executed in the same order as they appear in
the code. First, you see filter: for all elements, then length: for the elements left after filtering, and then the output of the
two last lines.
List processing
Sequence
Now let's write the same with sequences:
fun main() {
//sampleStart
val words = "The quick brown fox jumps over the lazy dog".split(" ")
//convert the List to a Sequence
val wordsSequence = words.asSequence()
The output of this code shows that the filter() and map() functions are called only when building the result list. So, you first
798
see the line of text “Lengths of..†and then the sequence processing starts. Note that for elements left after filtering,
the map executes before filtering the next element. When the result size reaches 4, the processing stops because it's the
largest possible size that take(4) can return.
Sequences processing
In this example, the sequence processing takes 18 steps instead of 23 steps for doing the same with lists.
Collection
operations
overview
The Kotlin standard library offers a broad variety of functions for performing operations on collections. This includes
simple operations, such as getting or adding elements, as well as more complex ones including search, sorting, filtering,
transformations, and so on.
Extension
and
member
functions
Collection operations are declared in the standard library in two ways: member functions of collection interfaces and
extension functions.
Member functions define operations that are essential for a collection type. For example, Collection contains the function
isEmpty() for checking its emptiness; List contains get() for index access to elements, and so on.
When you create your own implementations of collection interfaces, you must implement their member functions. To
make the creation of new implementations easier, use the skeletal implementations of collection interfaces from the
standard library: AbstractCollection, AbstractList, AbstractSet, AbstractMap, and their mutable counterparts.
Other collection operations are declared as extension functions. These are filtering, transformation, ordering, and other
799
collection processing functions.
Common
operations
Common operations are available for both read-only and mutable collections. Common operations fall into these groups:
Transformations
Filtering
Grouping
Ordering
Aggregate operations
Operations described on these pages return their results without affecting the original collection. For example, a filtering
operation produces a new collection that contains all the elements matching the filtering predicate. Results of such
operations should be either stored in variables, or used in some other way, for example, passed in other functions.
fun main() {
//sampleStart
val numbers = listOf("one", "two", "three", "four")
numbers.filter { it.length > 3 } // nothing happens with `numbers`, result is lost
println("numbers are still $numbers")
val longerThan3 = numbers.filter { it.length > 3 } // result is stored in `longerThan3`
println("numbers longer than 3 chars are $longerThan3")
//sampleEnd
}
For certain collection operations, there is an option to specify the destination object. Destination is a mutable collection to
which the function appends its resulting items instead of returning them in a new object. For performing operations with
destinations, there are separate functions with the To postfix in their names, for example, filterTo() instead of filter() or
associateTo() instead of associate(). These functions take the destination collection as an additional parameter.
fun main() {
//sampleStart
val numbers = listOf("one", "two", "three", "four")
val filterResults = mutableListOf<String>() //destination object
numbers.filterTo(filterResults) { it.length > 3 }
numbers.filterIndexedTo(filterResults) { index, _ -> index == 0 }
println(filterResults) // contains results of both operations
//sampleEnd
}
800
For convenience, these functions return the destination collection back, so you can create it right in the corresponding
argument of the function call:
fun main() {
val numbers = listOf("one", "two", "three", "four")
//sampleStart
// filter numbers right into a new hash set,
// thus eliminating duplicates in the result
val result = numbers.mapTo(HashSet()) { it.length }
println("distinct item lengths are $result")
//sampleEnd
}
Functions with destination are available for filtering, association, grouping, flattening, and other operations. For the
complete list of destination operations see the Kotlin collections reference.
Write
operations
For mutable collections, there are also write operations that change the collection state. Such operations include adding,
removing, and updating elements. Write operations are listed in the Write operations and corresponding sections of List-
specific operations and Map specific operations.
For certain operations, there are pairs of functions for performing the same operation: one applies the operation in-place
and the other returns the result as a separate collection. For example, sort() sorts a mutable collection in-place, so its
state changes; sorted() creates a new collection that contains the same elements in the sorted order.
fun main() {
//sampleStart
val numbers = mutableListOf("one", "two", "three", "four")
val sortedNumbers = numbers.sorted()
println(numbers == sortedNumbers) // false
numbers.sort()
println(numbers == sortedNumbers) // true
//sampleEnd
}
Collection
transformation
operations
The Kotlin standard library provides a set of extension functions for collection transformations. These functions build new
collections from existing ones based on the transformation rules provided. In this page, we'll give an overview of the
available collection transformation functions.
801
Map
The mapping transformation creates a collection from the results of a function on the elements of another collection. The
basic mapping function is map(). It applies the given lambda function to each subsequent element and returns the list of
the lambda results. The order of results is the same as the original order of elements. To apply a transformation that
additionally uses the element index as an argument, use mapIndexed().
fun main() {
//sampleStart
val numbers = setOf(1, 2, 3)
println(numbers.map { it * 3 })
println(numbers.mapIndexed { idx, value -> value * idx })
//sampleEnd
}
If the transformation produces null on certain elements, you can filter out the null s from the result collection by calling the
mapNotNull() function instead of map(), or mapIndexedNotNull() instead of mapIndexed().
fun main() {
//sampleStart
val numbers = setOf(1, 2, 3)
println(numbers.mapNotNull { if ( it == 2) null else it * 3 })
println(numbers.mapIndexedNotNull { idx, value -> if (idx == 0) null else value * idx })
//sampleEnd
}
When transforming maps, you have two options: transform keys leaving values unchanged and vice versa. To apply a
given transformation to keys, use mapKeys(); in turn, mapValues() transforms values. Both functions use the
transformations that take a map entry as an argument, so you can operate both its key and value.
fun main() {
//sampleStart
val numbersMap = mapOf("key1" to 1, "key2" to 2, "key3" to 3, "key11" to 11)
println(numbersMap.mapKeys { it.key.uppercase() })
println(numbersMap.mapValues { it.value + it.key.length })
//sampleEnd
}
Zip
Zipping transformation is building pairs from elements with the same positions in both collections. In the Kotlin standard
library, this is done by the zip() extension function.
When called on a collection or an array with another collection (array) as an argument, zip() returns the List of Pair objects.
The elements of the receiver collection are the first elements in these pairs.
802
If the collections have different sizes, the result of the zip() is the smaller size; the last elements of the larger collection are
not included in the result.
fun main() {
//sampleStart
val colors = listOf("red", "brown", "grey")
val animals = listOf("fox", "bear", "wolf")
println(colors zip animals)
You can also call zip() with a transformation function that takes two parameters: the receiver element and the argument
element. In this case, the result List contains the return values of the transformation function called on pairs of the receiver
and the argument elements with the same positions.
fun main() {
//sampleStart
val colors = listOf("red", "brown", "grey")
val animals = listOf("fox", "bear", "wolf")
println(colors.zip(animals) { color, animal -> "The ${animal.replaceFirstChar {
it.uppercase() }} is $color"})
//sampleEnd
}
When you have a List of Pair s, you can do the reverse transformation – unzipping – that builds two lists from these
pairs:
The first list contains the first elements of each Pair in the original list.
fun main() {
//sampleStart
val numberPairs = listOf("one" to 1, "two" to 2, "three" to 3, "four" to 4)
println(numberPairs.unzip())
//sampleEnd
}
Associate
803
Association transformations allow building maps from the collection elements and certain values associated with them. In
different association types, the elements can be either keys or values in the association map.
The basic association function associateWith() creates a Map in which the elements of the original collection are keys, and
values are produced from them by the given transformation function. If two elements are equal, only the last one remains
in the map.
fun main() {
//sampleStart
val numbers = listOf("one", "two", "three", "four")
println(numbers.associateWith { it.length })
//sampleEnd
}
For building maps with collection elements as values, there is the function associateBy(). It takes a function that returns a
key based on an element's value. If two elements' keys are equal, only the last one remains in the map.
fun main() {
//sampleStart
val numbers = listOf("one", "two", "three", "four")
println(numbers.associateBy { it.first().uppercaseChar() })
println(numbers.associateBy(keySelector = { it.first().uppercaseChar() }, valueTransform = {
it.length }))
//sampleEnd
}
Another way to build maps in which both keys and values are somehow produced from collection elements is the function
associate(). It takes a lambda function that returns a Pair: the key and the value of the corresponding map entry.
Note that associate() produces short-living Pair objects which may affect the performance. Thus, associate() should be
used when the performance isn't critical or it's more preferable than other options.
An example of the latter is when a key and the corresponding value are produced from an element together.
fun main() {
data class FullName (val firstName: String, val lastName: String)
//sampleStart
val names = listOf("Alice Adams", "Brian Brown", "Clara Campbell")
println(names.associate { name -> parseFullName(name).let { it.lastName to it.firstName } })
804
//sampleEnd
}
Here we call a transform function on an element first, and then build a pair from the properties of that function's result.
Flatten
If you operate nested collections, you may find the standard library functions that provide flat access to nested collection
elements useful.
The first function is flatten(). You can call it on a collection of collections, for example, a List of Set s. The function returns
a single List of all the elements of the nested collections.
fun main() {
//sampleStart
val numberSets = listOf(setOf(1, 2, 3), setOf(4, 5, 6), setOf(1, 2))
println(numberSets.flatten())
//sampleEnd
}
Another function – flatMap() provides a flexible way to process nested collections. It takes a function that maps a
collection element to another collection. As a result, flatMap() returns a single list of its return values on all the elements.
So, flatMap() behaves as a subsequent call of map() (with a collection as a mapping result) and flatten().
fun main() {
//sampleStart
val containers = listOf(
StringContainer(listOf("one", "two", "three")),
StringContainer(listOf("four", "five", "six")),
StringContainer(listOf("seven", "eight"))
)
println(containers.flatMap { it.values })
//sampleEnd
}
String
representation
If you need to retrieve the collection content in a readable format, use functions that transform the collections to strings:
joinToString() and joinTo().
joinToString() builds a single String from the collection elements based on the provided arguments. joinTo() does the same
but appends the result to the given Appendable object.
When called with the default arguments, the functions return the result similar to calling toString() on the collection: a
805
String of elements' string representations separated by commas with spaces.
fun main() {
//sampleStart
val numbers = listOf("one", "two", "three", "four")
println(numbers)
println(numbers.joinToString())
val listString = StringBuffer("The list of numbers: ")
numbers.joinTo(listString)
println(listString)
//sampleEnd
}
To build a custom string representation, you can specify its parameters in function arguments separator, prefix, and
postfix. The resulting string will start with the prefix and end with the postfix. The separator will come after each element
except the last.
fun main() {
//sampleStart
val numbers = listOf("one", "two", "three", "four")
println(numbers.joinToString(separator = " | ", prefix = "start: ", postfix = ": end"))
//sampleEnd
}
For bigger collections, you may want to specify the limit – a number of elements that will be included into result. If the
collection size exceeds the limit, all the other elements will be replaced with a single value of the truncated argument.
fun main() {
//sampleStart
val numbers = (1..100).toList()
println(numbers.joinToString(limit = 10, truncated = "<...>"))
//sampleEnd
}
Finally, to customize the representation of elements themselves, provide the transform function.
fun main() {
//sampleStart
val numbers = listOf("one", "two", "three", "four")
println(numbers.joinToString { "Element: ${it.uppercase()}"})
//sampleEnd
}
806
Filtering
collections
Filtering is one of the most popular tasks in collection processing. In Kotlin, filtering conditions are defined by predicates
– lambda functions that take a collection element and return a boolean value: true means that the given element
matches the predicate, false means the opposite.
The standard library contains a group of extension functions that let you filter collections in a single call. These functions
leave the original collection unchanged, so they are available for both mutable and read-only collections. To operate the
filtering result, you should assign it to a variable or chain the functions after filtering.
Filter
by
predicate
The basic filtering function is filter(). When called with a predicate, filter() returns the collection elements that match it. For
both List and Set, the resulting collection is a List, for Map it's a Map as well.
fun main() {
//sampleStart
val numbers = listOf("one", "two", "three", "four")
val longerThan3 = numbers.filter { it.length > 3 }
println(longerThan3)
The predicates in filter() can only check the values of the elements. If you want to use element positions in the filter, use
filterIndexed(). It takes a predicate with two arguments: the index and the value of an element.
To filter collections by negative conditions, use filterNot(). It returns a list of elements for which the predicate yields false.
fun main() {
//sampleStart
val numbers = listOf("one", "two", "three", "four")
val filteredIdx = numbers.filterIndexed { index, s -> (index != 0) && (s.length < 5) }
val filteredNot = numbers.filterNot { it.length <= 3 }
println(filteredIdx)
println(filteredNot)
//sampleEnd
}
There are also functions that narrow the element type by filtering elements of a given type:
filterIsInstance() returns collection elements of a given type. Being called on a List<Any>, filterIsInstance<T>() returns a
List<T>, thus allowing you to call functions of the T type on its items.
807
fun main() {
//sampleStart
val numbers = listOf(null, 1, "two", 3.0, "four")
println("All String elements in upper case:")
numbers.filterIsInstance<String>().forEach {
println(it.uppercase())
}
//sampleEnd
}
filterNotNull() returns all non-null elements. Being called on a List<T?>, filterNotNull() returns a List<T: Any>, thus
allowing you to treat the elements as non-null objects.
fun main() {
//sampleStart
val numbers = listOf(null, "one", "two", null)
numbers.filterNotNull().forEach {
println(it.length) // length is unavailable for nullable Strings
}
//sampleEnd
}
Partition
Another filtering function – partition() – filters a collection by a predicate and keeps the elements that don't match it in
a separate list. So, you have a Pair of List s as a return value: the first list containing elements that match the predicate
and the second one containing everything else from the original collection.
fun main() {
//sampleStart
val numbers = listOf("one", "two", "three", "four")
val (match, rest) = numbers.partition { it.length > 3 }
println(match)
println(rest)
//sampleEnd
}
Test
predicates
Finally, there are functions that simply test a predicate against collection elements:
any() returns true if at least one element matches the given predicate.
none() returns true if none of the elements match the given predicate.
all() returns true if all elements match the given predicate. Note that all() returns true when called with any valid
predicate on an empty collection. Such behavior is known in logic as vacuous truth.
808
fun main() {
//sampleStart
val numbers = listOf("one", "two", "three", "four")
println(numbers.any { it.endsWith("e") })
println(numbers.none { it.endsWith("a") })
println(numbers.all { it.endsWith("e") })
any() and none() can also be used without a predicate: in this case they just check the collection emptiness. any() returns
true if there are elements and false if there aren't; none() does the opposite.
fun main() {
//sampleStart
val numbers = listOf("one", "two", "three", "four")
val empty = emptyList<String>()
println(numbers.any())
println(empty.any())
println(numbers.none())
println(empty.none())
//sampleEnd
}
Plus
and
minus
operators
In Kotlin, plus (+) and minus (-) operators are defined for collections. They take a collection as the first operand; the
second operand can be either an element or another collection. The return value is a new read-only collection:
The result of plus contains the elements from the original collection and from the second operand.
The result of minus contains the elements of the original collection except the elements from the second operand. If it's
an element, minus removes its first occurrence; if it's a collection, all occurrences of its elements are removed.
fun main() {
//sampleStart
val numbers = listOf("one", "two", "three", "four")
For the details on plus and minus operators for maps, see Map specific operations. The augmented assignment operators
809
plusAssign (+=) and minusAssign (-=) are also defined for collections. However, for read-only collections, they actually
use the plus or minus operators and try to assign the result to the same variable. Thus, they are available only on var read-
only collections. For mutable collections, they modify the collection if it's a val. For more details see Collection write
operations.
Grouping
The Kotlin standard library provides extension functions for grouping collection elements. The basic function groupBy()
takes a lambda function and returns a Map. In this map, each key is the lambda result and the corresponding value is the
List of elements on which this result is returned. This function can be used, for example, to group a list of String s by their
first letter.
You can also call groupBy() with a second lambda argument – a value transformation function. In the result map of
groupBy() with two lambdas, the keys produced by keySelector function are mapped to the results of the value
transformation function instead of the original elements.
fun main() {
//sampleStart
val numbers = listOf("one", "two", "three", "four", "five")
println(numbers.groupBy { it.first().uppercase() })
println(numbers.groupBy(keySelector = { it.first() }, valueTransform = { it.uppercase() }))
//sampleEnd
}
If you want to group elements and then apply an operation to all groups at one time, use the function groupingBy(). It
returns an instance of the Grouping type. The Grouping instance lets you apply operations to all groups in a lazy manner:
the groups are actually built right before the operation execution.
fold() and reduce() perform fold and reduce operations on each group as a separate collection and return the results.
aggregate() applies a given operation subsequently to all the elements in each group and returns the result. This is the
generic way to perform any operations on a Grouping. Use it to implement custom operations when fold or reduce are
not enough.
fun main() {
//sampleStart
val numbers = listOf("one", "two", "three", "four", "five", "six")
println(numbers.groupingBy { it.first() }.eachCount())
//sampleEnd
}
Retrieve
collection
parts
810
The Kotlin standard library contains extension functions for retrieving parts of a collection. These functions provide a
variety of ways to select elements for the result collection: listing their positions explicitly, specifying the result size, and
others.
Slice
slice() returns a list of the collection elements with given indices. The indices may be passed either as a range or as a
collection of integer values.
fun main() {
//sampleStart
val numbers = listOf("one", "two", "three", "four", "five", "six")
println(numbers.slice(1..3))
println(numbers.slice(0..4 step 2))
println(numbers.slice(setOf(3, 5, 0)))
//sampleEnd
}
Take
and
drop
To get the specified number of elements starting from the first, use the take() function. For getting the last elements, use
takeLast(). When called with a number larger than the collection size, both functions return the whole collection.
To take all the elements except a given number of first or last elements, call the drop() and dropLast() functions
respectively.
fun main() {
//sampleStart
val numbers = listOf("one", "two", "three", "four", "five", "six")
println(numbers.take(3))
println(numbers.takeLast(3))
println(numbers.drop(1))
println(numbers.dropLast(5))
//sampleEnd
}
You can also use predicates to define the number of elements for taking or dropping. There are four functions similar to
the ones described above:
takeWhile() is take() with a predicate: it takes the elements up to but excluding the first one not matching the predicate.
If the first collection element doesn't match the predicate, the result is empty.
takeLastWhile() is similar to takeLast(): it takes the range of elements matching the predicate from the end of the
collection. The first element of the range is the element next to the last element not matching the predicate. If the last
collection element doesn't match the predicate, the result is empty;
811
dropWhile() is the opposite to takeWhile() with the same predicate: it returns the elements from the first one not
matching the predicate to the end.
dropLastWhile() is the opposite to takeLastWhile() with the same predicate: it returns the elements from the beginning
to the last one not matching the predicate.
fun main() {
//sampleStart
val numbers = listOf("one", "two", "three", "four", "five", "six")
println(numbers.takeWhile { !it.startsWith('f') })
println(numbers.takeLastWhile { it != "three" })
println(numbers.dropWhile { it.length == 3 })
println(numbers.dropLastWhile { it.contains('i') })
//sampleEnd
}
Chunked
To break a collection onto parts of a given size, use the chunked() function. chunked() takes a single argument – the
size of the chunk – and returns a List of List s of the given size. The first chunk starts from the first element and contains
the size elements, the second chunk holds the next size elements, and so on. The last chunk may have a smaller size.
fun main() {
//sampleStart
val numbers = (0..13).toList()
println(numbers.chunked(3))
//sampleEnd
}
You can also apply a transformation for the returned chunks right away. To do this, provide the transformation as a
lambda function when calling chunked(). The lambda argument is a chunk of the collection. When chunked() is called with
a transformation, the chunks are short-living List s that should be consumed right in that lambda.
fun main() {
//sampleStart
val numbers = (0..13).toList()
println(numbers.chunked(3) { it.sum() }) // `it` is a chunk of the original collection
//sampleEnd
}
Windowed
You can retrieve all possible ranges of the collection elements of a given size. The function for getting them is called
windowed(): it returns a list of element ranges that you would see if you were looking at the collection through a sliding
812
window of the given size. Unlike chunked(), windowed() returns element ranges (windows) starting from each collection
element. All the windows are returned as elements of a single List.
fun main() {
//sampleStart
val numbers = listOf("one", "two", "three", "four", "five")
println(numbers.windowed(3))
//sampleEnd
}
step defines a distance between first elements of two adjacent windows. By default the value is 1, so the result
contains windows starting from all elements. If you increase the step to 2, you will receive only windows starting from
odd elements: first, third, and so on.
partialWindows includes windows of smaller sizes that start from the elements at the end of the collection. For
example, if you request windows of three elements, you can't build them for the last two elements. Enabling
partialWindows in this case includes two more lists of sizes 2 and 1.
Finally, you can apply a transformation to the returned ranges right away. To do this, provide the transformation as a
lambda function when calling windowed().
fun main() {
//sampleStart
val numbers = (1..10).toList()
println(numbers.windowed(3, step = 2, partialWindows = true))
println(numbers.windowed(3) { it.sum() })
//sampleEnd
}
To build two-element windows, there is a separate function - zipWithNext(). It creates pairs of adjacent elements of the
receiver collection. Note that zipWithNext() doesn't break the collection into pairs; it creates a Pair for each element
except the last one, so its result on [1, 2, 3, 4] is [[1, 2], [2, 3], [3, 4]], not [[1, 2], [3, 4]]. zipWithNext() can be called with a
transformation function as well; it should take two elements of the receiver collection as arguments.
fun main() {
//sampleStart
val numbers = listOf("one", "two", "three", "four", "five")
println(numbers.zipWithNext())
println(numbers.zipWithNext() { s1, s2 -> s1.length > s2.length})
//sampleEnd
}
Retrieve
single
elements
813
Kotlin collections provide a set of functions for retrieving single elements from collections. Functions described on this
page apply to both lists and sets.
As the definition of list says, a list is an ordered collection. Hence, every element of a list has its position that you can use
for referring. In addition to functions described on this page, lists offer a wider set of ways to retrieve and search for
elements by indices. For more details, see List-specific operations.
In turn, set is not an ordered collection by definition. However, the Kotlin Set stores elements in certain orders. These can
be the order of insertion (in LinkedHashSet), natural sorting order (in SortedSet), or another order. The order of a set of
elements can also be unknown. In such cases, the elements are still ordered somehow, so the functions that rely on the
element positions still return their results. However, such results are unpredictable to the caller unless they know the
specific implementation of Set used.
Retrieve
by
position
For retrieving an element at a specific position, there is the function elementAt(). Call it with the integer number as an
argument, and you'll receive the collection element at the given position. The first element has the position 0, and the last
one is (size - 1).
elementAt() is useful for collections that do not provide indexed access, or are not statically known to provide one. In case
of List, it's more idiomatic to use indexed access operator (get() or []).
fun main() {
//sampleStart
val numbers = linkedSetOf("one", "two", "three", "four", "five")
println(numbers.elementAt(3))
There are also useful aliases for retrieving the first and the last element of the collection: first() and last().
fun main() {
//sampleStart
val numbers = listOf("one", "two", "three", "four", "five")
println(numbers.first())
println(numbers.last())
//sampleEnd
}
To avoid exceptions when retrieving element with non-existing positions, use safe variations of elementAt():
elementAtOrNull() returns null when the specified position is out of the collection bounds.
elementAtOrElse() additionally takes a lambda function that maps an Int argument to an instance of the collection
element type. When called with an out-of-bounds position, the elementAtOrElse() returns the result of the lambda on
814
the given value.
fun main() {
//sampleStart
val numbers = listOf("one", "two", "three", "four", "five")
println(numbers.elementAtOrNull(5))
println(numbers.elementAtOrElse(5) { index -> "The value for index $index is undefined"})
//sampleEnd
}
Retrieve
by
condition
Functions first() and last() also let you search a collection for elements matching a given predicate. When you call first()
with a predicate that tests a collection element, you'll receive the first element on which the predicate yields true. In turn,
last() with a predicate returns the last element matching it.
fun main() {
//sampleStart
val numbers = listOf("one", "two", "three", "four", "five", "six")
println(numbers.first { it.length > 3 })
println(numbers.last { it.startsWith("f") })
//sampleEnd
}
If no elements match the predicate, both functions throw exceptions. To avoid them, use firstOrNull() and lastOrNull()
instead: they return null if no matching elements are found.
fun main() {
//sampleStart
val numbers = listOf("one", "two", "three", "four", "five", "six")
println(numbers.firstOrNull { it.length > 6 })
//sampleEnd
}
fun main() {
//sampleStart
val numbers = listOf(1, 2, 3, 4)
println(numbers.find { it % 2 == 0 })
println(numbers.findLast { it % 2 == 0 })
//sampleEnd
815
}
Retrieve
with
selector
If you need to map the collection before retrieving the element, there is a function firstNotNullOf(). It combines 2 actions:
firstNotNullOf() throws the NoSuchElementException if the resulting collection doesn't have a non-null element. Use the
counterpart firstNotNullOfOrNull() to return null in this case.
fun main() {
//sampleStart
val list = listOf<Any>(0, "true", false)
// Converts each element to string and returns the first one that has required length
val longEnough = list.firstNotNullOf { item -> item.toString().takeIf { it.length >= 4 } }
println(longEnough)
//sampleEnd
}
Random
element
If you need to retrieve an arbitrary element of a collection, call the random() function. You can call it without arguments or
with a Random object as a source of the randomness.
fun main() {
//sampleStart
val numbers = listOf(1, 2, 3, 4)
println(numbers.random())
//sampleEnd
}
On empty collections, random() throws an exception. To receive null instead, use randomOrNull()
Check
element
existence
To check the presence of an element in a collection, use the contains() function. It returns true if there is a collection
element that equals() the function argument. You can call contains() in the operator form with the in keyword.
To check the presence of multiple instances together at once, call containsAll() with a collection of these instances as an
argument.
816
fun main() {
//sampleStart
val numbers = listOf("one", "two", "three", "four", "five", "six")
println(numbers.contains("four"))
println("zero" in numbers)
println(numbers.containsAll(listOf("four", "two")))
println(numbers.containsAll(listOf("one", "zero")))
//sampleEnd
}
Additionally, you can check if the collection contains any elements by calling isEmpty() or isNotEmpty().
fun main() {
//sampleStart
val numbers = listOf("one", "two", "three", "four", "five", "six")
println(numbers.isEmpty())
println(numbers.isNotEmpty())
val empty = emptyList<String>()
println(empty.isEmpty())
println(empty.isNotEmpty())
//sampleEnd
}
Ordering
The order of elements is an important aspect of certain collection types. For example, two lists of the same elements are
not equal if their elements are ordered differently.
First, there is natural order. It is defined for inheritors of the Comparable interface. Natural order is used for sorting them
when no other order is specified.
Numeric types use the traditional numerical order: 1 is greater than 0; -3.4f is greater than -5f, and so on.
Char and String use the lexicographical order: b is greater than a; world is greater than hello.
To define a natural order for a user-defined type, make the type an inheritor of Comparable. This requires implementing
the compareTo() function. compareTo() must take another object of the same type as an argument and return an integer
value showing which object is greater:
817
Below is a class for ordering versions that consist of the major and the minor part.
fun main() {
println(Version(1, 2) > Version(1, 3))
println(Version(2, 0) > Version(1, 5))
}
Custom orders let you sort instances of any type in a way you like. Particularly, you can define an order for non-
comparable objects or define an order other than natural for a comparable type. To define a custom order for a type,
create a Comparator for it. Comparator contains the compare() function: it takes two instances of a class and returns the
integer result of the comparison between them. The result is interpreted in the same way as the result of a compareTo() as
is described above.
fun main() {
//sampleStart
val lengthComparator = Comparator { str1: String, str2: String -> str1.length - str2.length }
println(listOf("aaa", "bb", "c").sortedWith(lengthComparator))
//sampleEnd
}
Having the lengthComparator, you are able to arrange strings by their length instead of the default lexicographical order.
A shorter way to define a Comparator is the compareBy() function from the standard library. compareBy() takes a lambda
function that produces a Comparable value from an instance and defines the custom order as the natural order of the
produced values.
With compareBy(), the length comparator from the example above looks like this:
fun main() {
//sampleStart
println(listOf("aaa", "bb", "c").sortedWith(compareBy { it.length }))
//sampleEnd
}
The Kotlin collections package provides functions for sorting collections in natural, custom, and even random orders. On
this page, we'll describe sorting functions that apply to read-only collections. These functions return their result as a new
collection containing the elements of the original collection in the requested order. To learn about functions for sorting
mutable collections in place, see the List-specific operations.
818
Natural
order
The basic functions sorted() and sortedDescending() return elements of a collection sorted into ascending and descending
sequence according to their natural order. These functions apply to collections of Comparable elements.
fun main() {
//sampleStart
val numbers = listOf("one", "two", "three", "four")
Custom
orders
For sorting in custom orders or sorting non-comparable objects, there are the functions sortedBy() and
sortedByDescending(). They take a selector function that maps collection elements to Comparable values and sort the
collection in natural order of that values.
fun main() {
//sampleStart
val numbers = listOf("one", "two", "three", "four")
To define a custom order for the collection sorting, you can provide your own Comparator. To do this, call the
sortedWith() function passing in your Comparator. With this function, sorting strings by their length looks like this:
fun main() {
//sampleStart
val numbers = listOf("one", "two", "three", "four")
println("Sorted by length ascending: ${numbers.sortedWith(compareBy { it.length })}")
//sampleEnd
}
Reverse
order
You can retrieve the collection in the reversed order using the reversed() function.
fun main() {
819
//sampleStart
val numbers = listOf("one", "two", "three", "four")
println(numbers.reversed())
//sampleEnd
}
reversed() returns a new collection with the copies of the elements. So, if you change the original collection later, this
won't affect the previously obtained results of reversed().
returns a reversed view of the same collection instance, so it may be more lightweight and preferable than reversed() if
the original list is not going to change.
fun main() {
//sampleStart
val numbers = listOf("one", "two", "three", "four")
val reversedNumbers = numbers.asReversed()
println(reversedNumbers)
//sampleEnd
}
If the original list is mutable, all its changes reflect in its reversed views and vice versa.
fun main() {
//sampleStart
val numbers = mutableListOf("one", "two", "three", "four")
val reversedNumbers = numbers.asReversed()
println(reversedNumbers)
numbers.add("five")
println(reversedNumbers)
//sampleEnd
}
However, if the mutability of the list is unknown or the source is not a list at all, reversed() is more preferable since its
result is a copy that won't change in the future.
Random
order
Finally, there is a function that returns a new List containing the collection elements in a random order - shuffled(). You
can call it without arguments or with a Random object.
fun main() {
//sampleStart
val numbers = listOf("one", "two", "three", "four")
println(numbers.shuffled())
//sampleEnd
}
820
Aggregate
operations
Kotlin collections contain functions for commonly used aggregate operations – operations that return a single value
based on the collection content. Most of them are well known and work the same way as they do in other languages:
minOrNull() and maxOrNull() return the smallest and the largest element respectively. On empty collections, they return
null.
fun main() {
val numbers = listOf(6, 42, 10, 4)
println("Count: ${numbers.count()}")
println("Max: ${numbers.maxOrNull()}")
println("Min: ${numbers.minOrNull()}")
println("Average: ${numbers.average()}")
println("Sum: ${numbers.sum()}")
}
There are also functions for retrieving the smallest and the largest elements by certain selector function or custom
Comparator:
maxByOrNull() and minByOrNull() take a selector function and return the element for which it returns the largest or the
smallest value.
maxWithOrNull() and minWithOrNull() take a Comparator object and return the largest or smallest element according to
that Comparator.
These functions return null on empty collections. There are also alternatives for maxByOrNull() and minByOrNull(): maxOf()
and minOf(), which do the same but throw a NoSuchElementException on empty collections.
fun main() {
//sampleStart
val numbers = listOf(5, 42, 10, 4)
val min3Remainder = numbers.minByOrNull { it % 3 }
println(min3Remainder)
Besides regular sum(), there is an advanced summation function sumOf() that takes a selector function and returns the
sum of its application to all collection elements. Selector can return different numeric types: Int, Long, Double, UInt, and
821
ULong (also BigInteger and BigDecimal on the JVM).
fun main() {
//sampleStart
val numbers = listOf(5, 42, 10, 4)
println(numbers.sumOf { it * 2 })
println(numbers.sumOf { it.toDouble() / 2 })
//sampleEnd
}
Fold
and
reduce
For more specific cases, there are the functions reduce() and fold() that apply the provided operation to the collection
elements sequentially and return the accumulated result. The operation takes two arguments: the previously accumulated
value and the collection element.
The difference between the two functions is that fold() takes an initial value and uses it as the accumulated value on the
first step, whereas the first step of reduce() uses the first and the second elements as operation arguments on the first
step.
fun main() {
//sampleStart
val numbers = listOf(5, 2, 10, 4)
The example above shows the difference: fold() is used for calculating the sum of doubled elements. If you pass the same
function to reduce(), it will return another result because it uses the list's first and second elements as arguments on the
first step, so the first element won't be doubled.
To apply a function to elements in the reverse order, use functions reduceRight() and foldRight(). They work in a way
similar to fold() and reduce() but start from the last element and then continue to previous. Note that when folding or
reducing right, the operation arguments change their order: first goes the element, and then the accumulated value.
fun main() {
//sampleStart
val numbers = listOf(5, 2, 10, 4)
val sumDoubledRight = numbers.foldRight(0) { element, sum -> sum + element * 2 }
println(sumDoubledRight)
822
//sampleEnd
}
You can also apply operations that take element indices as parameters. For this purpose, use functions reduceIndexed()
and foldIndexed() passing element index as the first argument of the operation.
Finally, there are functions that apply such operations to collection elements from right to left - reduceRightIndexed() and
foldRightIndexed().
fun main() {
//sampleStart
val numbers = listOf(5, 2, 10, 4)
val sumEven = numbers.foldIndexed(0) { idx, sum, element -> if (idx % 2 == 0) sum + element
else sum }
println(sumEven)
All reduce operations throw an exception on empty collections. To receive null instead, use their *OrNull() counterparts:
reduceOrNull()
reduceRightOrNull()
reduceIndexedOrNull()
reduceRightIndexedOrNull()
For cases where you want to save intermediate accumulator values, there are functions runningFold() (or its synonym
scan()) and runningReduce().
fun main() {
//sampleStart
val numbers = listOf(0, 1, 2, 3, 4, 5)
val runningReduceSum = numbers.runningReduce { sum, item -> sum + item }
val runningFoldSum = numbers.runningFold(10) { sum, item -> sum + item }
//sampleEnd
val transform = { index: Int, element: Int -> "N = ${index + 1}: $element" }
println(runningReduceSum.mapIndexed(transform).joinToString("\n", "Sum of first N elements
with runningReduce:\n"))
println(runningFoldSum.mapIndexed(transform).joinToString("\n", "Sum of first N elements with
runningFold:\n"))
}
823
Collection
write
operations
Mutable collections support operations for changing the collection contents, for example, adding or removing elements.
On this page, we'll describe write operations available for all implementations of MutableCollection. For more specific
operations available for List and Map, see List-specific Operations and Map Specific Operations respectively.
Adding
elements
To add a single element to a list or a set, use the add() function. The specified object is appended to the end of the
collection.
fun main() {
//sampleStart
val numbers = mutableListOf(1, 2, 3, 4)
numbers.add(5)
println(numbers)
//sampleEnd
}
addAll() adds every element of the argument object to a list or a set. The argument can be an Iterable, a Sequence, or an
Array. The types of the receiver and the argument may be different, for example, you can add all items from a Set to a
List.
When called on lists, addAll() adds new elements in the same order as they go in the argument. You can also call addAll()
specifying an element position as the first argument. The first element of the argument collection will be inserted at this
position. Other elements of the argument collection will follow it, shifting the receiver elements to the end.
fun main() {
//sampleStart
val numbers = mutableListOf(1, 2, 5, 6)
numbers.addAll(arrayOf(7, 8))
println(numbers)
numbers.addAll(2, setOf(3, 4))
println(numbers)
//sampleEnd
}
You can also add elements using the in-place version of the plus operator- plusAssign (+=) When applied to a mutable
collection, += appends the second operand (an element or another collection) to the end of the collection.
fun main() {
//sampleStart
val numbers = mutableListOf("one", "two")
numbers += "three"
println(numbers)
numbers += listOf("four", "five")
824
println(numbers)
//sampleEnd
}
Removing
elements
To remove an element from a mutable collection, use the remove() function. remove() accepts the element value and
removes one occurrence of this value.
fun main() {
//sampleStart
val numbers = mutableListOf(1, 2, 3, 4, 3)
numbers.remove(3) // removes the first `3`
println(numbers)
numbers.remove(5) // removes nothing
println(numbers)
//sampleEnd
}
For removing multiple elements at once, there are the following functions :
removeAll() removes all elements that are present in the argument collection. Alternatively, you can call it with a
predicate as an argument; in this case the function removes all elements for which the predicate yields true.
retainAll() is the opposite of removeAll(): it removes all elements except the ones from the argument collection. When
used with a predicate, it leaves only elements that match it.
fun main() {
//sampleStart
val numbers = mutableListOf(1, 2, 3, 4)
println(numbers)
numbers.retainAll { it >= 3 }
println(numbers)
numbers.clear()
println(numbers)
Another way to remove elements from a collection is with the minusAssign (-=) operator – the in-place version of minus.
The second argument can be a single instance of the element type or another collection. With a single element on the
right-hand side, -= removes the first occurrence of it. In turn, if it's a collection, all occurrences of its elements are
removed. For example, if a list contains duplicate elements, they are removed at once. The second operand can contain
elements that are not present in the collection. Such elements don't affect the operation execution.
825
fun main() {
//sampleStart
val numbers = mutableListOf("one", "two", "three", "three", "four")
numbers -= "three"
println(numbers)
numbers -= listOf("four", "five")
//numbers -= listOf("four") // does the same as above
println(numbers)
//sampleEnd
}
Updating
elements
Lists and maps also provide operations for updating elements. They are described in List-specific Operations and Map
Specific Operations. For sets, updating doesn't make sense since it's actually removing an element and adding another
one.
List-specific
operations
List is the most popular type of built-in collection in Kotlin. Index access to the elements of lists provides a powerful set of
operations for lists.
Retrieve
elements
by
index
Lists support all common operations for element retrieval: elementAt(), first(), last(), and others listed in Retrieve single
elements. What is specific for lists is index access to the elements, so the simplest way to read an element is retrieving it
by index. That is done with the get() function with the index passed in the argument or the shorthand [index] syntax.
If the list size is less than the specified index, an exception is thrown. There are two other functions that help you avoid
such exceptions:
getOrElse() lets you provide the function for calculating the default value to return if the index isn't present in the
collection.
fun main() {
//sampleStart
val numbers = listOf(1, 2, 3, 4)
println(numbers.get(0))
println(numbers[0])
//numbers.get(5) // exception!
println(numbers.getOrNull(5)) // null
println(numbers.getOrElse(5, {it})) // 5
826
//sampleEnd
}
Retrieve
list
parts
In addition to common operations for Retrieving Collection Parts, lists provide the subList() function that returns a view of
the specified elements range as a list. Thus, if an element of the original collection changes, it also changes in the
previously created sublists and vice versa.
fun main() {
//sampleStart
val numbers = (0..13).toList()
println(numbers.subList(3, 6))
//sampleEnd
}
Find
element
positions
Linear
search
In any lists, you can find the position of an element using the functions indexOf() and lastIndexOf(). They return the first
and the last position of an element equal to the given argument in the list. If there are no such elements, both functions
return -1.
fun main() {
//sampleStart
val numbers = listOf(1, 2, 3, 4, 2, 5)
println(numbers.indexOf(2))
println(numbers.lastIndexOf(2))
//sampleEnd
}
There is also a pair of functions that take a predicate and search for elements matching it:
indexOfFirst() returns the index of the first element matching the predicate or -1 if there are no such elements.
indexOfLast() returns the index of the last element matching the predicate or -1 if there are no such elements.
fun main() {
//sampleStart
val numbers = mutableListOf(1, 2, 3, 4)
println(numbers.indexOfFirst { it > 2})
println(numbers.indexOfLast { it % 2 == 1})
//sampleEnd
}
827
Binary
search
in
sorted
lists
There is one more way to search elements in lists – binary search. It works significantly faster than other built-in search
functions but requires the list to be sorted in ascending order according to a certain ordering: natural or another one
provided in the function parameter. Otherwise, the result is undefined.
To search an element in a sorted list, call the binarySearch() function passing the value as an argument. If such an
element exists, the function returns its index; otherwise, it returns (-insertionPoint - 1) where insertionPoint is the index
where this element should be inserted so that the list remains sorted. If there is more than one element with the given
value, the search can return any of their indices.
You can also specify an index range to search in: in this case, the function searches only between two provided indices.
fun main() {
//sampleStart
val numbers = mutableListOf("one", "two", "three", "four")
numbers.sort()
println(numbers)
println(numbers.binarySearch("two")) // 3
println(numbers.binarySearch("z")) // -5
println(numbers.binarySearch("two", 0, 2)) // -3
//sampleEnd
}
fun main() {
//sampleStart
val productList = listOf(
Product("WebStorm", 49.0),
Product("AppCode", 99.0),
Product("DotTrace", 129.0),
Product("ReSharper", 149.0))
Here's a list of Product instances that aren't Comparable and a Comparator that defines the order: product p1 precedes
product p2 if p1 's price is less than p2 's price. So, having a list sorted ascending according to this order, we use
binarySearch() to find the index of the specified Product.
828
Custom comparators are also handy when a list uses an order different from natural one, for example, a case-insensitive
order for String elements.
fun main() {
//sampleStart
val colors = listOf("Blue", "green", "ORANGE", "Red", "yellow")
println(colors.binarySearch("RED", String.CASE_INSENSITIVE_ORDER)) // 3
//sampleEnd
}
import kotlin.math.sign
//sampleStart
data class Product(val name: String, val price: Double)
fun main() {
val productList = listOf(
Product("WebStorm", 49.0),
Product("AppCode", 99.0),
Product("DotTrace", 129.0),
Product("ReSharper", 149.0))
Both comparator and comparison binary search can be performed for list ranges as well.
List
write
operations
In addition to the collection modification operations described in Collection write operations, mutable lists support
specific write operations. Such operations use the index to access elements to broaden the list modification capabilities.
Add
To add elements to a specific position in a list, use add() and addAll() providing the position for element insertion as an
additional argument. All elements that come after the position shift to the right.
829
fun main() {
//sampleStart
val numbers = mutableListOf("one", "five", "six")
numbers.add(1, "two")
numbers.addAll(2, listOf("three", "four"))
println(numbers)
//sampleEnd
}
Update
Lists also offer a function to replace an element at a given position - set() and its operator form []. set() doesn't change the
indexes of other elements.
fun main() {
//sampleStart
val numbers = mutableListOf("one", "five", "three")
numbers[1] = "two"
println(numbers)
//sampleEnd
}
fill() simply replaces all the collection elements with the specified value.
fun main() {
//sampleStart
val numbers = mutableListOf(1, 2, 3, 4)
numbers.fill(3)
println(numbers)
//sampleEnd
}
Remove
To remove an element at a specific position from a list, use the removeAt() function providing the position as an
argument. All indices of elements that come after the element being removed will decrease by one.
fun main() {
//sampleStart
val numbers = mutableListOf(1, 2, 3, 4, 3)
numbers.removeAt(1)
println(numbers)
//sampleEnd
}
Sort
830
In Collection Ordering, we describe operations that retrieve collection elements in specific orders. For mutable lists, the
standard library offers similar extension functions that perform the same ordering operations in place. When you apply
such an operation to a list instance, it changes the order of elements in that exact instance.
The in-place sorting functions have similar names to the functions that apply to read-only lists, but without the ed/d suffix:
sort* instead of sorted* in the names of all sorting functions: sort(), sortDescending(), sortBy(), and so on.
asReversed() called on a mutable list returns another mutable list which is a reversed view of the original list. Changes in
that view are reflected in the original list. The following example shows sorting functions for mutable lists:
fun main() {
//sampleStart
val numbers = mutableListOf("one", "two", "three", "four")
numbers.sort()
println("Sort into ascending: $numbers")
numbers.sortDescending()
println("Sort into descending: $numbers")
numbers.sortBy { it.length }
println("Sort into ascending by length: $numbers")
numbers.sortByDescending { it.last() }
println("Sort into descending by the last letter: $numbers")
numbers.sortWith(compareBy<String> { it.length }.thenBy { it })
println("Sort by Comparator: $numbers")
numbers.shuffle()
println("Shuffle: $numbers")
numbers.reverse()
println("Reverse: $numbers")
//sampleEnd
}
Set-specific
operations
The Kotlin collections package contains extension functions for popular operations on sets: finding intersections, merging,
or subtracting collections from each other.
To merge two collections into one, use the union() function. It can be used in the infix form a union b. Note that for
ordered collections the order of the operands is important: in the resulting collection, the elements of the first operand go
before the elements of the second.
To find an intersection between two collections (elements present in both of them), use intersect(). To find collection
elements not present in another collection, use subtract(). Both these functions can be called in the infix form as well, for
831
example, a intersect b.
fun main() {
//sampleStart
val numbers = setOf("one", "two", "three")
Note that set operations are supported by List as well. However, the result of set operations on lists is still a Set, so all the
duplicate elements are removed.
Map-specific
operations
In maps, types of both keys and values are user-defined. Key-based access to map entries enables various map-specific
processing capabilities from getting a value by key to separate filtering of keys and values. On this page, we provide
descriptions of the map processing functions from the standard library.
Retrieve
keys
and
values
For retrieving a value from a map, you must provide its key as an argument of the get() function. The shorthand [key]
syntax is also supported. If the given key is not found, it returns null. There is also the function getValue() which has
slightly different behavior: it throws an exception if the key is not found in the map. Additionally, you have two more
options to handle the key absence:
getOrElse() works the same way as for lists: the values for non-existent keys are returned from the given lambda
function.
getOrDefault() returns the specified default value if the key is not found.
fun main() {
//sampleStart
val numbersMap = mapOf("one" to 1, "two" to 2, "three" to 3)
println(numbersMap.get("one"))
println(numbersMap["one"])
println(numbersMap.getOrDefault("four", 10))
println(numbersMap["five"]) // null
//numbersMap.getValue("six") // exception!
//sampleEnd
}
To perform operations on all keys or all values of a map, you can retrieve them from the properties keys and values
832
accordingly. keys is a set of all map keys and values is a collection of all map values.
fun main() {
//sampleStart
val numbersMap = mapOf("one" to 1, "two" to 2, "three" to 3)
println(numbersMap.keys)
println(numbersMap.values)
//sampleEnd
}
Filter
You can filter maps with the filter() function as well as other collections. When calling filter() on a map, pass to it a
predicate with a Pair as an argument. This enables you to use both the key and the value in the filtering predicate.
fun main() {
//sampleStart
val numbersMap = mapOf("key1" to 1, "key2" to 2, "key3" to 3, "key11" to 11)
val filteredMap = numbersMap.filter { (key, value) -> key.endsWith("1") && value > 10}
println(filteredMap)
//sampleEnd
}
There are also two specific ways for filtering maps: by keys and by values. For each way, there is a function: filterKeys()
and filterValues(). Both return a new map of entries which match the given predicate. The predicate for filterKeys() checks
only the element keys, the one for filterValues() checks only values.
fun main() {
//sampleStart
val numbersMap = mapOf("key1" to 1, "key2" to 2, "key3" to 3, "key11" to 11)
val filteredKeysMap = numbersMap.filterKeys { it.endsWith("1") }
val filteredValuesMap = numbersMap.filterValues { it < 10 }
println(filteredKeysMap)
println(filteredValuesMap)
//sampleEnd
}
Plus
and
minus
operators
Due to the key access to elements, plus (+) and minus (-) operators work for maps differently than for other collections.
plus returns a Map that contains elements of its both operands: a Map on the left and a Pair or another Map on the right.
When the right-hand side operand contains entries with keys present in the left-hand side Map, the result map contains
the entries from the right side.
833
fun main() {
//sampleStart
val numbersMap = mapOf("one" to 1, "two" to 2, "three" to 3)
println(numbersMap + Pair("four", 4))
println(numbersMap + Pair("one", 10))
println(numbersMap + mapOf("five" to 5, "one" to 11))
//sampleEnd
}
minus creates a Map from entries of a Map on the left except those with keys from the right-hand side operand. So, the
right-hand side operand can be either a single key or a collection of keys: list, set, and so on.
fun main() {
//sampleStart
val numbersMap = mapOf("one" to 1, "two" to 2, "three" to 3)
println(numbersMap - "one")
println(numbersMap - listOf("two", "four"))
//sampleEnd
}
For details on using plusAssign (+=) and minusAssign (-=) operators on mutable maps, see Map write operations below.
Map
write
operations
Mutable maps offer map-specific write operations. These operations let you change the map content using the key-based
access to the values.
Values can be updated. In turn, keys never change: once you add an entry, its key is constant.
For each key, there is always a single value associated with it. You can add and remove whole entries.
Below are descriptions of the standard library functions for write operations available on mutable maps.
Add
and
update
entries
To add a new key-value pair to a mutable map, use put(). When a new entry is put into a LinkedHashMap (the default map
implementation), it is added so that it comes last when iterating the map. In sorted maps, the positions of new elements
are defined by the order of their keys.
fun main() {
//sampleStart
val numbersMap = mutableMapOf("one" to 1, "two" to 2)
numbersMap.put("three", 3)
println(numbersMap)
//sampleEnd
}
834
To add multiple entries at a time, use putAll(). Its argument can be a Map or a group of Pair s: Iterable, Sequence, or
Array.
fun main() {
//sampleStart
val numbersMap = mutableMapOf("one" to 1, "two" to 2, "three" to 3)
numbersMap.putAll(setOf("four" to 4, "five" to 5))
println(numbersMap)
//sampleEnd
}
Both put() and putAll() overwrite the values if the given keys already exist in the map. Thus, you can use them to update
values of map entries.
fun main() {
//sampleStart
val numbersMap = mutableMapOf("one" to 1, "two" to 2)
val previousValue = numbersMap.put("one", 11)
println("value associated with 'one', before: $previousValue, after: ${numbersMap["one"]}")
println(numbersMap)
//sampleEnd
}
You can also add new entries to maps using the shorthand operator form. There are two ways:
fun main() {
//sampleStart
val numbersMap = mutableMapOf("one" to 1, "two" to 2)
numbersMap["three"] = 3 // calls numbersMap.put("three", 3)
numbersMap += mapOf("four" to 4, "five" to 5)
println(numbersMap)
//sampleEnd
}
When called with the key present in the map, operators overwrite the values of the corresponding entries.
Remove
entries
To remove an entry from a mutable map, use the remove() function. When calling remove(), you can pass either a key or a
whole key-value-pair. If you specify both the key and value, the element with this key will be removed only if its value
matches the second argument.
835
fun main() {
//sampleStart
val numbersMap = mutableMapOf("one" to 1, "two" to 2, "three" to 3)
numbersMap.remove("one")
println(numbersMap)
numbersMap.remove("three", 4) //doesn't remove anything
println(numbersMap)
//sampleEnd
}
You can also remove entries from a mutable map by their keys or values. To do this, call remove() on the map's keys or
values providing the key or the value of an entry. When called on values, remove() removes only the first entry with the
given value.
fun main() {
//sampleStart
val numbersMap = mutableMapOf("one" to 1, "two" to 2, "three" to 3, "threeAgain" to 3)
numbersMap.keys.remove("one")
println(numbersMap)
numbersMap.values.remove(3)
println(numbersMap)
//sampleEnd
}
fun main() {
//sampleStart
val numbersMap = mutableMapOf("one" to 1, "two" to 2, "three" to 3)
numbersMap -= "two"
println(numbersMap)
numbersMap -= "five" //doesn't remove anything
println(numbersMap)
//sampleEnd
}
Scope
functions
The Kotlin standard library contains several functions whose sole purpose is to execute a block of code within the context
of an object. When you call such a function on an object with a lambda expression provided, it forms a temporary scope.
In this scope, you can access the object without its name. Such functions are called scope functions. There are five of
them: let, run, with, apply, and also.
Basically, these functions do the same: execute a block of code on an object. What's different is how this object becomes
available inside the block and what is the result of the whole expression.
836
data class Person(var name: String, var age: Int, var city: String) {
fun moveTo(newCity: String) { city = newCity }
fun incrementAge() { age++ }
}
fun main() {
//sampleStart
Person("Alice", 20, "Amsterdam").let {
println(it)
it.moveTo("London")
it.incrementAge()
println(it)
}
//sampleEnd
}
If you write the same without let, you'll have to introduce a new variable and repeat its name whenever you use it.
data class Person(var name: String, var age: Int, var city: String) {
fun moveTo(newCity: String) { city = newCity }
fun incrementAge() { age++ }
}
fun main() {
//sampleStart
val alice = Person("Alice", 20, "Amsterdam")
println(alice)
alice.moveTo("London")
alice.incrementAge()
println(alice)
//sampleEnd
}
The scope functions do not introduce any new technical capabilities, but they can make your code more concise and
readable.
Due to the similar nature of scope functions, choosing the right one for your case can be a bit tricky. The choice mainly
depends on your intent and the consistency of use in your project. Below we'll provide detailed descriptions of the
distinctions between scope functions and the conventions on their usage.
Function
selection
To help you choose the right scope function for your purpose, we provide the table of key differences between them.
837
Function Object reference Return value Is extension function
with this Lambda result No: takes the context object as an argument.
The detailed information about the differences is provided in the dedicated sections below.
Here is a short guide for choosing scope functions depending on the intended purpose:
The use cases of different functions overlap, so that you can choose the functions based on the specific conventions
used in your project or team.
Although the scope functions are a way of making the code more concise, avoid overusing them: it can decrease your
code readability and lead to errors. Avoid nesting scope functions and be careful when chaining them: it's easy to get
confused about the current context object and the value of this or it.
Distinctions
Because the scope functions are all quite similar in nature, it's important to understand the differences between them.
There are two main differences between each scope function:
Context
object:
this
or
it
Inside the lambda of a scope function, the context object is available by a short reference instead of its actual name.
Each scope function uses one of two ways to access the context object: as a lambda receiver (this) or as a lambda
838
argument (it). Both provide the same capabilities, so we'll describe the pros and cons of each for different cases and
provide recommendations on their use.
fun main() {
val str = "Hello"
// this
str.run {
println("The receiver string length: $length")
//println("The receiver string length: ${this.length}") // does the same
}
// it
str.let {
println("The receiver string's length is ${it.length}")
}
}
this
run, with, and apply refer to the context object as a lambda receiver - by keyword this. Hence, in their lambdas, the object
is available as it would be in ordinary class functions. In most cases, you can omit this when accessing the members of
the receiver object, making the code shorter. On the other hand, if this is omitted, it can be hard to distinguish between
the receiver members and external objects or functions. So, having the context object as a receiver (this) is recommended
for lambdas that mainly operate on the object members: call its functions or assign properties.
data class Person(var name: String, var age: Int = 0, var city: String = "")
fun main() {
//sampleStart
val adam = Person("Adam").apply {
age = 20 // same as this.age = 20 or adam.age = 20
city = "London"
}
println(adam)
//sampleEnd
}
it
In turn, let and also have the context object as a lambda argument. If the argument name is not specified, the object is
accessed by the implicit default name it. it is shorter than this and expressions with it are usually easier for reading.
However, when calling the object functions or properties you don't have the object available implicitly like this. Hence,
having the context object as it is better when the object is mostly used as an argument in function calls. it is also better if
you use multiple variables in the code block.
import kotlin.random.Random
fun main() {
839
//sampleStart
fun getRandomInt(): Int {
return Random.nextInt(100).also {
writeToLog("getRandomInt() generated value $it")
}
}
val i = getRandomInt()
println(i)
//sampleEnd
}
Additionally, when you pass the context object as an argument, you can provide a custom name for the context object
inside the scope.
import kotlin.random.Random
fun main() {
//sampleStart
fun getRandomInt(): Int {
return Random.nextInt(100).also { value ->
writeToLog("getRandomInt() generated value $value")
}
}
val i = getRandomInt()
println(i)
//sampleEnd
}
Return
value
The scope functions differ by the result they return:
These two options let you choose the proper function depending on what you do next in your code.
Context object
The return value of apply and also is the context object itself. Hence, they can be included into call chains as side steps:
you can continue chaining function calls on the same object after them.
fun main() {
//sampleStart
val numberList = mutableListOf<Double>()
numberList.also { println("Populating the list") }
.apply {
840
add(2.71)
add(3.14)
add(1.0)
}
.also { println("Sorting the list") }
.sort()
//sampleEnd
println(numberList)
}
They also can be used in return statements of functions returning the context object.
import kotlin.random.Random
fun main() {
//sampleStart
fun getRandomInt(): Int {
return Random.nextInt(100).also {
writeToLog("getRandomInt() generated value $it")
}
}
val i = getRandomInt()
//sampleEnd
}
Lambda result
let, run, and with return the lambda result. So, you can use them when assigning the result to a variable, chaining
operations on the result, and so on.
fun main() {
//sampleStart
val numbers = mutableListOf("one", "two", "three")
val countEndsWithE = numbers.run {
add("four")
add("five")
count { it.endsWith("e") }
}
println("There are $countEndsWithE elements that end with e.")
//sampleEnd
}
Additionally, you can ignore the return value and use a scope function to create a temporary scope for variables.
fun main() {
//sampleStart
val numbers = mutableListOf("one", "two", "three")
with(numbers) {
val firstItem = first()
841
val lastItem = last()
println("First item: $firstItem, last item: $lastItem")
}
//sampleEnd
}
Functions
To help you choose the right scope function for your case, we'll describe them in detail and provide usage
recommendations. Technically, functions are interchangeable in many cases, so the examples show the conventions that
define the common usage style.
let
The context object is available as an argument (it). The return value is the lambda result.
let can be used to invoke one or more functions on results of call chains. For example, the following code prints the results
of two operations on a collection:
fun main() {
//sampleStart
val numbers = mutableListOf("one", "two", "three", "four", "five")
val resultList = numbers.map { it.length }.filter { it > 3 }
println(resultList)
//sampleEnd
}
fun main() {
//sampleStart
val numbers = mutableListOf("one", "two", "three", "four", "five")
numbers.map { it.length }.filter { it > 3 }.let {
println(it)
// and more function calls if needed
}
//sampleEnd
}
If the code block contains a single function with it as an argument, you can use the method reference (::) instead of the
lambda:
fun main() {
//sampleStart
val numbers = mutableListOf("one", "two", "three", "four", "five")
numbers.map { it.length }.filter { it > 3 }.let(::println)
//sampleEnd
}
842
let is often used for executing a code block only with non-null values. To perform actions on a non-null object, use the
safe call operator ?. on it and call let with the actions in its lambda.
fun main() {
//sampleStart
val str: String? = "Hello"
//processNonNullString(str) // compilation error: str can be null
val length = str?.let {
println("let() called on $it")
processNonNullString(it) // OK: 'it' is not null inside '?.let { }'
it.length
}
//sampleEnd
}
Another case for using let is introducing local variables with a limited scope for improving code readability. To define a
new variable for the context object, provide its name as the lambda argument so that it can be used instead of the default
it.
fun main() {
//sampleStart
val numbers = listOf("one", "two", "three", "four")
val modifiedFirstItem = numbers.first().let { firstItem ->
println("The first item of the list is '$firstItem'")
if (firstItem.length >= 5) firstItem else "!" + firstItem + "!"
}.uppercase()
println("First item after modifications: '$modifiedFirstItem'")
//sampleEnd
}
with
A non-extension function: the context object is passed as an argument, but inside the lambda, it's available as a receiver
(this). The return value is the lambda result.
We recommend with for calling functions on the context object without providing the lambda result. In the code, with can
be read as “ with this object, do the following.â€
fun main() {
//sampleStart
val numbers = mutableListOf("one", "two", "three")
with(numbers) {
println("'with' is called with argument $this")
println("It contains $size elements")
}
//sampleEnd
}
Another use case for with is introducing a helper object whose properties or functions will be used for calculating a value.
843
fun main() {
//sampleStart
val numbers = mutableListOf("one", "two", "three")
val firstAndLast = with(numbers) {
"The first element is ${first()}," +
" the last element is ${last()}"
}
println(firstAndLast)
//sampleEnd
}
run
The context object is available as a receiver (this). The return value is the lambda result.
run does the same as with but invokes as let- as an extension function of the context object.
run is useful when your lambda contains both the object initialization and the computation of the return value.
fun main() {
//sampleStart
val service = MultiportService("https://example.kotlinlang.org", 80)
Besides calling run on a receiver object, you can use it as a non-extension function. Non-extension run lets you execute a
block of several statements where an expression is required.
fun main() {
//sampleStart
val hexNumberRegex = run {
val digits = "0-9"
val hexDigits = "A-Fa-f"
val sign = "+-"
Regex("[$sign]?[$digits$hexDigits]+")
}
844
for (match in hexNumberRegex.findAll("+1234 -FFFF not-a-number")) {
println(match.value)
}
//sampleEnd
}
apply
The context object is available as a receiver (this). The return value is the object itself.
Use apply for code blocks that don't return a value and mainly operate on the members of the receiver object. The
common case for apply is the object configuration. Such calls can be read as “ apply the following assignments to the
object.â€
data class Person(var name: String, var age: Int = 0, var city: String = "")
fun main() {
//sampleStart
val adam = Person("Adam").apply {
age = 32
city = "London"
}
println(adam)
//sampleEnd
}
Having the receiver as the return value, you can easily include apply into call chains for more complex processing.
also
The context object is available as an argument (it). The return value is the object itself.
also is good for performing some actions that take the context object as an argument. Use also for actions that need a
reference rather to the object than to its properties and functions, or when you don't want to shadow this reference from
an outer scope.
When you see also in the code, you can read it as “ and also do the following with the object.â€
fun main() {
//sampleStart
val numbers = mutableListOf("one", "two", "three")
numbers
.also { println("The list elements before adding new one: $it") }
.add("four")
//sampleEnd
}
takeIf
and
takeUnless
845
In addition to scope functions, the standard library contains the functions takeIf and takeUnless. These functions let you
embed checks of the object state in call chains.
When called on an object with a predicate provided, takeIf returns this object if it matches the predicate. Otherwise, it
returns null. So, takeIf is a filtering function for a single object. In turn, takeUnless returns the object if it doesn't match the
predicate and null if it does. The object is available as a lambda argument (it).
import kotlin.random.*
fun main() {
//sampleStart
val number = Random.nextInt(100)
When chaining other functions after takeIf and takeUnless, don't forget to perform the null check or the safe call (?.)
because their return value is nullable.
fun main() {
//sampleStart
val str = "Hello"
val caps = str.takeIf { it.isNotEmpty() }?.uppercase()
//val caps = str.takeIf { it.isNotEmpty() }.uppercase() //compilation error
println(caps)
//sampleEnd
}
takeIf and takeUnless are especially useful together with scope functions. A good case is chaining them with let for
running a code block on objects that match the given predicate. To do this, call takeIf on the object and then call let with a
safe call (?). For objects that don't match the predicate, takeIf returns null and let isn't invoked.
fun main() {
//sampleStart
fun displaySubstringPosition(input: String, sub: String) {
input.indexOf(sub).takeIf { it >= 0 }?.let {
println("The substring $sub is found in $input.")
println("Its start position is $it.")
}
}
displaySubstringPosition("010000011", "11")
displaySubstringPosition("010000011", "12")
//sampleEnd
}
This is how the same function looks without the standard library functions:
fun main() {
846
//sampleStart
fun displaySubstringPosition(input: String, sub: String) {
val index = input.indexOf(sub)
if (index >= 0) {
println("The substring $sub is found in $input.")
println("Its start position is $index.")
}
}
displaySubstringPosition("010000011", "11")
displaySubstringPosition("010000011", "12")
//sampleEnd
}
Opt-in
requirements
The opt-in requirement annotations @RequiresOptIn and @OptIn are Experimental. They may be dropped or
changed at any time. Opt-in is required (see details below). Use them only for evaluation purposes. We
appreciate your feedback on it in YouTrack.
@RequireOptIn and @OptIn annotations were introduced in 1.3.70 to replace previously used @Experimental
and @UseExperimental; at the same time, -opt-in compiler option replaced -Xuse-experimental.
The Kotlin standard library provides a mechanism for requiring and giving explicit consent for using certain elements of
APIs. This mechanism lets library developers inform users of their APIs about specific conditions that require opt-in, for
example, if an API is in the experimental state and is likely to change in the future.
To prevent potential issues, the compiler warns users of such APIs about these conditions and requires them to opt in
before using the API.
Opt
in
to
using
API
If a library author marks a declaration from a library's API as requiring opt-in, you should give an explicit consent for using
it in your code. There are several ways to opt in to such APIs, all applicable without technical limitations. You are free to
choose the way that you find best for your situation.
Propagating
opt-in
When you use an API in the code intended for third-party use (a library), you can propagate its opt-in requirement to your
API as well. To do this, annotate your declaration with the opt-in requirement annotation of the API used in its body. This
enables you to use API elements that require opt-in.
// Library code
847
@RequiresOptIn(message = "This API is experimental. It may be changed in the future without
notice.")
@Retention(AnnotationRetention.BINARY)
@Target(AnnotationTarget.CLASS, AnnotationTarget.FUNCTION)
annotation class MyDateTime // Opt-in requirement annotation
@MyDateTime
class DateProvider // A class requiring opt-in
// Client code
fun getYear(): Int {
val dateProvider: DateProvider // Error: DateProvider requires opt-in
// ...
}
@MyDateTime
fun getDate(): Date {
val dateProvider: DateProvider // OK: the function requires opt-in as well
// ...
}
fun displayDate() {
println(getDate()) // Error: getDate() requires opt-in
}
As you can see in this example, the annotated function appears to be a part of the @MyDateTime API. So, such an opt-in
propagates the opt-in requirement to the client code; its clients will see the same warning message and be required to
consent as well.
Implicit usages of APIs that require opt-in also require opt-in. If an API element doesn't have an opt-in requirement
annotation but its signature includes a type declared as requiring opt-in, its usage will still raise a warning. See the
example below.
// Client code
fun getDate(dateProvider: DateProvider): Date { // Error: DateProvider requires opt-in
// ...
}
fun displayDate() {
println(getDate()) // Warning: the signature of getDate() contains DateProvider, which
requires opt-in
}
To use multiple APIs that require opt-in, mark the declaration with all their opt-in requirement annotations.
Non-propagating
opt-in
In modules that don't expose their own API, such as applications, you can opt in to using APIs without propagating the
opt-in requirement to your code. In this case, mark your declaration with @OptIn passing the opt-in requirement
annotation as its argument:
// Library code
848
@RequiresOptIn(message = "This API is experimental. It may be changed in the future without
notice.")
@Retention(AnnotationRetention.BINARY)
@Target(AnnotationTarget.CLASS, AnnotationTarget.FUNCTION)
annotation class MyDateTime // Opt-in requirement annotation
@MyDateTime
class DateProvider // A class requiring opt-in
// Client code
@OptIn(MyDateTime::class)
fun getDate(): Date { // Uses DateProvider; doesn't propagate the opt-in requirement
val dateProvider: DateProvider
// ...
}
fun displayDate() {
println(getDate()) // OK: opt-in is not required
}
When somebody calls the function getDate(), they won't be informed about the opt-in requirements for APIs used in its
body.
Note that if @OptIn applies to the declaration whose signature contains a type declared as requiring opt-in, the opt-in will
still propagate:
// Client code
@OptIn(MyDateTime::class)
fun getDate(dateProvider: DateProvider): Date { // Has DateProvider as a part of a signature;
propagates the opt-in requirement
// ...
}
fun displayDate() {
println(getDate()) // Warning: getDate() requires opt-in
}
To use an API that requires opt-in in all functions and classes in a file, add the file-level annotation @file:OptIn to the top
of the file before the package specification and imports.
// Client code
@file:OptIn(MyDateTime::class)
Module-wide
opt-in
If you don't want to annotate every usage of APIs that require opt-in, you can opt in to them for your whole module. To
opt in to using an API in a module, compile it with the argument -opt-in, specifying the fully qualified name of the opt-in
requirement annotation of the API you use: -opt-in=org.mylibrary.OptInAnnotation. Compiling with this argument has the
same effect as if every declaration in the module had the annotation @OptIn(OptInAnnotation::class).
If you build your module with Gradle, you can add arguments like this:
849
Kotlin
tasks.withType<org.jetbrains.kotlin.gradle.tasks.KotlinCompile>().configureEach {
kotlinOptions.freeCompilerArgs += "-opt-in=org.mylibrary.OptInAnnotation"
}
Groovy
tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).configureEach {
kotlinOptions {
freeCompilerArgs += "-opt-in=org.mylibrary.OptInAnnotation"
}
}
Kotlin
sourceSets {
all {
languageSettings.optIn("org.mylibrary.OptInAnnotation")
}
}
Groovy
sourceSets {
all {
languageSettings {
optIn('org.mylibrary.OptInAnnotation')
}
}
}
<build>
<plugins>
<plugin>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-plugin</artifactId>
<version>${kotlin.version}</version>
<executions>...</executions>
<configuration>
<args>
<arg>-opt-in=org.mylibrary.OptInAnnotation</arg>
</args>
</configuration>
</plugin>
850
</plugins>
</build>
To opt in to multiple APIs on the module level, add one of the described arguments for each opt-in requirement marker
used in your module.
Require
opt-in
for
API
Create
opt-in
requirement
annotations
If you want to require explicit consent to using your module's API, create an annotation class to use as an opt-in
requirement annotation. This class must be annotated with @RequiresOptIn:
@RequiresOptIn
@Retention(AnnotationRetention.BINARY)
@Target(AnnotationTarget.CLASS, AnnotationTarget.FUNCTION)
annotation class MyDateTime
No parameters.
RequiresOptIn.Level.ERROR. Opt-in is mandatory. Otherwise, the code that uses marked API won't compile. Default
level.
RequiresOptIn.Level.WARNING. Opt-in is not mandatory, but advisable. Without it, the compiler raises a warning.
To set the desired level, specify the level parameter of the @RequiresOptIn annotation.
Additionally, you can provide a message to inform API users about special condition of using the API. The compiler will
show it to users that use the API without opt-in.
If you publish multiple independent features that require opt-in, declare an annotation for each. This makes the use of API
safer for your clients: they can use only the features that they explicitly accept. This also lets you remove the opt-in
requirements from the features independently.
851
Mark
API
elements
To require an opt-in to using an API element, annotate its declaration with an opt-in requirement annotation:
@MyDateTime
class DateProvider
@MyDateTime
fun getTime(): Time {}
Note that for some language elements, an opt-in requirement annotation is not applicable:
Overriding methods can only have opt-in annotations that are present on their basic declarations.
You cannot annotate a backing field or a getter of a property, just the property itself.
Opt-in
requirements
for
pre-stable
APIs
If you use opt-in requirements for features that are not stable yet, carefully handle the API graduation to avoid breaking
the client code.
Once your pre-stable API graduates and is released in a stable state, remove its opt-in requirement annotations from
declarations. The clients will be able to use them without restriction. However, you should leave the annotation classes in
modules so that the existing client code remains compatible.
To let the API users update their modules accordingly (remove the annotations from their code and recompile), mark the
annotations as @Deprecated and provide the explanation in the deprecation message.
@Deprecated("This opt-in requirement is not used anymore. Remove its usages from your code.")
@RequiresOptIn
annotation class ExperimentalDateTime
Experimental
status
of
the
opt-in
requirements
The opt-in requirement mechanism is currently experimental. This means that in future releases it may be changed in
ways that make it incompatible.
To make the users of annotations @OptIn and @RequiresOptIn aware of their experimental status, the compiler raises
warnings when compiling the code with these annotations:
This class can only be used with the compiler argument '-opt-in=kotlin.RequiresOptIn'
852
Coroutines
guide
Kotlin, as a language, provides only minimal low-level APIs in its standard library to enable various other libraries to utilize
coroutines. Unlike many other languages with similar capabilities, async and await are not keywords in Kotlin and are not
even part of its standard library. Moreover, Kotlin's concept of suspending function provides a safer and less error-prone
abstraction for asynchronous operations than futures and promises.
kotlinx.coroutines is a rich library for coroutines developed by JetBrains. It contains a number of high-level coroutine-
enabled primitives that this guide covers, including launch, async and others.
This is a guide on core features of kotlinx.coroutines with a series of examples, divided up into different topics.
In order to use coroutines as well as follow the examples in this guide, you need to add a dependency on the kotlinx-
coroutines-core module as explained in the project README.
Table
of
contents
Coroutines basics
Asynchronous Flow
Channels
Additional
references
Guide to UI programming with coroutines
853
Coroutines
basics
This section covers basic coroutine concepts.
Your
first
coroutine
A coroutine is an instance of suspendable computation. It is conceptually similar to a thread, in the sense that it takes a
block of code to run that works concurrently with the rest of the code. However, a coroutine is not bound to any particular
thread. It may suspend its execution in one thread and resume in another one.
Coroutines can be thought of as light-weight threads, but there is a number of important differences that make their real-
life usage very different from threads.
import kotlinx.coroutines.*
//sampleStart
fun main() = runBlocking { // this: CoroutineScope
launch { // launch a new coroutine and continue
delay(1000L) // non-blocking delay for 1 second (default time unit is ms)
println("World!") // print after delay
}
println("Hello") // main coroutine continues while a previous one is delayed
}
//sampleEnd
Hello
World!
launch is a coroutine builder. It launches a new coroutine concurrently with the rest of the code, which continues to work
independently. That's why Hello has been printed first.
delay is a special suspending function. It suspends the coroutine for a specific time. Suspending a coroutine does not
block the underlying thread, but allows other coroutines to run and use the underlying thread for their code.
runBlocking is also a coroutine builder that bridges the non-coroutine world of a regular fun main() and the code with
coroutines inside of runBlocking { ... } curly braces. This is highlighted in an IDE by this: CoroutineScope hint right after
the runBlocking opening curly brace.
854
If you remove or forget runBlocking in this code, you'll get an error on the launch call, since launch is declared only in the
CoroutineScope:
The name of runBlocking means that the thread that runs it (in this case — the main thread) gets blocked for the duration
of the call, until all the coroutines inside runBlocking { ... } complete their execution. You will often see runBlocking used
like that at the very top-level of the application and quite rarely inside the real code, as threads are expensive resources
and blocking them is inefficient and is often not desired.
Structured
concurrency
Coroutines follow a principle of structured concurrency which means that new coroutines can be only launched in a
specific CoroutineScope which delimits the lifetime of the coroutine. The above example shows that runBlocking
establishes the corresponding scope and that is why the previous example waits until World! is printed after a second's
delay and only then exits.
In the real application, you will be launching a lot of coroutines. Structured concurrency ensures that they are not lost and
do not leak. An outer scope cannot complete until all its children coroutines complete. Structured concurrency also
ensures that any errors in the code are properly reported and are never lost.
Extract
function
refactoring
Let's extract the block of code inside launch { ... } into a separate function. When you perform "Extract function"
refactoring on this code, you get a new function with the suspend modifier. This is your first suspending function.
Suspending functions can be used inside coroutines just like regular functions, but their additional feature is that they can,
in turn, use other suspending functions (like delay in this example) to suspend execution of a coroutine.
import kotlinx.coroutines.*
//sampleStart
fun main() = runBlocking { // this: CoroutineScope
launch { doWorld() }
println("Hello")
}
855
Scope
builder
In addition to the coroutine scope provided by different builders, it is possible to declare your own scope using the
coroutineScope builder. It creates a coroutine scope and does not complete until all launched children complete.
runBlocking and coroutineScope builders may look similar because they both wait for their body and all its children to
complete. The main difference is that the runBlocking method blocks the current thread for waiting, while coroutineScope
just suspends, releasing the underlying thread for other usages. Because of that difference, runBlocking is a regular
function and coroutineScope is a suspending function.
You can use coroutineScope from any suspending function. For example, you can move the concurrent printing of Hello
and World into a suspend fun doWorld() function:
import kotlinx.coroutines.*
//sampleStart
fun main() = runBlocking {
doWorld()
}
Hello
World!
Scope
builder
and
concurrency
A coroutineScope builder can be used inside any suspending function to perform multiple concurrent operations. Let's
launch two concurrent coroutines inside a doWorld suspending function:
import kotlinx.coroutines.*
//sampleStart
// Sequentially executes doWorld followed by "Done"
fun main() = runBlocking {
doWorld()
856
println("Done")
}
Both pieces of code inside launch { ... } blocks execute concurrently, with World 1 printed first, after a second from start,
and World 2 printed next, after two seconds from start. A coroutineScope in doWorld completes only after both are
complete, so doWorld returns and allows Done string to be printed only after that:
Hello
World 1
World 2
Done
An
explicit
job
A launch coroutine builder returns a Job object that is a handle to the launched coroutine and can be used to explicitly
wait for its completion. For example, you can wait for completion of the child coroutine and then print "Done" string:
import kotlinx.coroutines.*
857
You can get the full code here.
Hello
World!
Done
Coroutines
ARE
light-weight
Run the following code:
import kotlinx.coroutines.*
//sampleStart
fun main() = runBlocking {
repeat(100_000) { // launch a lot of coroutines
launch {
delay(5000L)
print(".")
}
}
}
//sampleEnd
It launches 100K coroutines and, after 5 seconds, each coroutine prints a dot.
Now, try that with threads (remove runBlocking, replace launch with thread, and replace delay with Thread.sleep). What
would happen? (Most likely your code will produce some sort of out-of-memory error)
Cancellation
and
timeouts
This section covers coroutine cancellation and timeouts.
Cancelling
coroutine
execution
In a long-running application you might need fine-grained control on your background coroutines. For example, a user
might have closed the page that launched a coroutine and now its result is no longer needed and its operation can be
cancelled. The launch function returns a Job that can be used to cancel the running coroutine:
858
import kotlinx.coroutines.*
As soon as main invokes job.cancel, we don't see any output from the other coroutine because it was cancelled. There is
also a Job extension function cancelAndJoin that combines cancel and join invocations.
Cancellation
is
cooperative
Coroutine cancellation is cooperative. A coroutine code has to cooperate to be cancellable. All the suspending functions
in kotlinx.coroutines are cancellable. They check for cancellation of coroutine and throw CancellationException when
cancelled. However, if a coroutine is working in a computation and does not check for cancellation, then it cannot be
cancelled, like the following example shows:
import kotlinx.coroutines.*
859
println("job: I'm sleeping ${i++} ...")
nextPrintTime += 500L
}
}
}
delay(1300L) // delay a bit
println("main: I'm tired of waiting!")
job.cancelAndJoin() // cancels the job and waits for its completion
println("main: Now I can quit.")
//sampleEnd
}
Run it to see that it continues to print "I'm sleeping" even after cancellation until the job completes by itself after five
iterations.
Making
computation
code
cancellable
There are two approaches to making computation code cancellable. The first one is to periodically invoke a suspending
function that checks for cancellation. There is a yield function that is a good choice for that purpose. The other one is to
explicitly check the cancellation status. Let us try the latter approach.
Replace while (i < 5) in the previous example with while (isActive) and rerun it.
import kotlinx.coroutines.*
860
As you can see, now this loop is cancelled. isActive is an extension property available inside the coroutine via the
CoroutineScope object.
Closing
resources
with
finally
Cancellable suspending functions throw CancellationException on cancellation which can be handled in the usual way.
For example, try {...} finally {...} expression and Kotlin use function execute their finalization actions normally when a
coroutine is cancelled:
import kotlinx.coroutines.*
Both join and cancelAndJoin wait for all finalization actions to complete, so the example above produces the following
output:
Run
non-cancellable
block
Any attempt to use a suspending function in the finally block of the previous example causes CancellationException,
because the coroutine running this code is cancelled. Usually, this is not a problem, since all well-behaving closing
operations (closing a file, cancelling a job, or closing any kind of a communication channel) are usually non-blocking and
861
do not involve any suspending functions. However, in the rare case when you need to suspend in a cancelled coroutine
you can wrap the corresponding code in withContext(NonCancellable) {...} using withContext function and
NonCancellable context as the following example shows:
import kotlinx.coroutines.*
Timeout
The most obvious practical reason to cancel execution of a coroutine is because its execution time has exceeded some
timeout. While you can manually track the reference to the corresponding Job and launch a separate coroutine to cancel
the tracked one after delay, there is a ready to use withTimeout function that does it. Look at the following example:
import kotlinx.coroutines.*
862
You can get the full code here.
Since cancellation is just an exception, all resources are closed in the usual way. You can wrap the code with timeout in a
try {...} catch (e: TimeoutCancellationException) {...} block if you need to do some additional action specifically on any
kind of timeout or use the withTimeoutOrNull function that is similar to withTimeout but returns null on timeout instead of
throwing an exception:
import kotlinx.coroutines.*
Asynchronous
timeout
and
resources
863
The timeout event in withTimeout is asynchronous with respect to the code running in its block and may happen at any
time, even right before the return from inside of the timeout block. Keep this in mind if you open or acquire some resource
inside the block that needs closing or release outside of the block.
For example, here we imitate a closeable resource with the Resource class, that simply keeps track of how many times it
was created by incrementing the acquired counter and decrementing this counter from its close function. Let us run a lot
of coroutines with the small timeout try acquire this resource from inside of the withTimeout block after a bit of delay and
release it from outside.
import kotlinx.coroutines.*
//sampleStart
var acquired = 0
class Resource {
init { acquired++ } // Acquire the resource
fun close() { acquired-- } // Release the resource
}
fun main() {
runBlocking {
repeat(100_000) { // Launch 100K coroutines
launch {
val resource = withTimeout(60) { // Timeout of 60 ms
delay(50) // Delay for 50 ms
Resource() // Acquire a resource and return it from withTimeout block
}
resource.close() // Release the resource
}
}
}
// Outside of runBlocking all coroutines have completed
println(acquired) // Print the number of resources still acquired
}
//sampleEnd
If you run the above code you'll see that it does not always print zero, though it may depend on the timings of your
machine you may need to tweak timeouts in this example to actually see non-zero values.
Note, that incrementing and decrementing acquired counter here from 100K coroutines is completely safe,
since it always happens from the same main thread. More on that will be explained in the next chapter on
coroutine context.
To workaround this problem you can store a reference to the resource in the variable as opposed to returning it from the
withTimeout block.
864
import kotlinx.coroutines.*
var acquired = 0
class Resource {
init { acquired++ } // Acquire the resource
fun close() { acquired-- } // Release the resource
}
fun main() {
//sampleStart
runBlocking {
repeat(100_000) { // Launch 100K coroutines
launch {
var resource: Resource? = null // Not acquired yet
try {
withTimeout(60) { // Timeout of 60 ms
delay(50) // Delay for 50 ms
resource = Resource() // Store a resource to the variable if acquired
}
// We can do something else with the resource here
} finally {
resource?.close() // Release the resource if it was acquired
}
}
}
}
// Outside of runBlocking all coroutines have completed
println(acquired) // Print the number of resources still acquired
//sampleEnd
}
Composing
suspending
functions
This section covers various approaches to composition of suspending functions.
Sequential
by
default
Assume that we have two suspending functions defined elsewhere that do something useful like some kind of remote
service call or computation. We just pretend they are useful, but actually each one just delays for a second for the
purpose of this example:
865
return 13
}
What do we do if we need them to be invoked sequentially — first doSomethingUsefulOne and then
doSomethingUsefulTwo, and compute the sum of their results? In practice, we do this if we use the result of the first
function to make a decision on whether we need to invoke the second one or to decide on how to invoke it.
We use a normal sequential invocation, because the code in the coroutine, just like in the regular code, is sequential by
default. The following example demonstrates it by measuring the total time it takes to execute both suspending functions:
import kotlinx.coroutines.*
import kotlin.system.*
The answer is 42
Completed in 2017 ms
Concurrent
using
async
What if there are no dependencies between invocations of doSomethingUsefulOne and doSomethingUsefulTwo and we
866
want to get the answer faster, by doing both concurrently? This is where async comes to help.
Conceptually, async is just like launch. It starts a separate coroutine which is a light-weight thread that works
concurrently with all the other coroutines. The difference is that launch returns a Job and does not carry any resulting
value, while async returns a Deferred — a light-weight non-blocking future that represents a promise to provide a result
later. You can use .await() on a deferred value to get its eventual result, but Deferred is also a Job, so you can cancel it if
needed.
import kotlinx.coroutines.*
import kotlin.system.*
The answer is 42
Completed in 1017 ms
This is twice as fast, because the two coroutines execute concurrently. Note that concurrency with coroutines is always
explicit.
Lazily
started
async
Optionally, async can be made lazy by setting its start parameter to CoroutineStart.LAZY. In this mode it only starts the
coroutine when its result is required by await, or if its Job 's start function is invoked. Run the following example:
import kotlinx.coroutines.*
867
import kotlin.system.*
The answer is 42
Completed in 1017 ms
So, here the two coroutines are defined but not executed as in the previous example, but the control is given to the
programmer on when exactly to start the execution by calling start. We first start one, then start two, and then await for
the individual coroutines to finish.
Note that if we just call await in println without first calling start on individual coroutines, this will lead to sequential
behavior, since await starts the coroutine execution and waits for its finish, which is not the intended use-case for
laziness. The use-case for async(start = CoroutineStart.LAZY) is a replacement for the standard lazy function in cases
when computation of the value involves suspending functions.
Async-style
functions
We can define async-style functions that invoke doSomethingUsefulOne and doSomethingUsefulTwo asynchronously
using the async coroutine builder using a GlobalScope reference to opt-out of the structured concurrency. We name such
functions with the "...Async" suffix to highlight the fact that they only start asynchronous computation and one needs to
use the resulting deferred value to get the result.
868
GlobalScope is a delicate API that can backfire in non-trivial ways, one of which will be explained below, so you
must explicitly opt-in into using GlobalScope with @OptIn(DelicateCoroutinesApi::class).
Note that these xxxAsync functions are not suspending functions. They can be used from anywhere. However, their use
always implies asynchronous (here meaning concurrent) execution of their action with the invoking code.
import kotlinx.coroutines.*
import kotlin.system.*
//sampleStart
// note that we don't have `runBlocking` to the right of `main` in this example
fun main() {
val time = measureTimeMillis {
// we can initiate async actions outside of a coroutine
val one = somethingUsefulOneAsync()
val two = somethingUsefulTwoAsync()
// but waiting for a result must involve either suspending or blocking.
// here we use `runBlocking { ... }` to block the main thread while waiting for the
result
runBlocking {
println("The answer is ${one.await() + two.await()}")
}
}
println("Completed in $time ms")
}
//sampleEnd
@OptIn(DelicateCoroutinesApi::class)
fun somethingUsefulOneAsync() = GlobalScope.async {
doSomethingUsefulOne()
}
@OptIn(DelicateCoroutinesApi::class)
fun somethingUsefulTwoAsync() = GlobalScope.async {
doSomethingUsefulTwo()
}
869
suspend fun doSomethingUsefulTwo(): Int {
delay(1000L) // pretend we are doing something useful here, too
return 29
}
This programming style with async functions is provided here only for illustration, because it is a popular style in
other programming languages. Using this style with Kotlin coroutines is strongly discouraged for the reasons
explained below.
Consider what happens if between the val one = somethingUsefulOneAsync() line and one.await() expression there is
some logic error in the code, and the program throws an exception, and the operation that was being performed by the
program aborts. Normally, a global error-handler could catch this exception, log and report the error for developers, but
the program could otherwise continue doing other operations. However, here we have somethingUsefulOneAsync still
running in the background, even though the operation that initiated it was aborted. This problem does not happen with
structured concurrency, as shown in the section below.
Structured
concurrency
with
async
Let us take the Concurrent using async example and extract a function that concurrently performs
doSomethingUsefulOne and doSomethingUsefulTwo and returns the sum of their results. Because the async coroutine
builder is defined as an extension on CoroutineScope, we need to have it in the scope and that is what the
coroutineScope function provides:
This way, if something goes wrong inside the code of the concurrentSum function, and it throws an exception, all the
coroutines that were launched in its scope will be cancelled.
import kotlinx.coroutines.*
import kotlin.system.*
870
}
We still have concurrent execution of both operations, as evident from the output of the above main function:
The answer is 42
Completed in 1017 ms
import kotlinx.coroutines.*
871
You can get the full code here.
Note how both the first async and the awaiting parent are cancelled on failure of one of the children (namely, two):
Coroutine
context
and
dispatchers
Coroutines always execute in some context represented by a value of the CoroutineContext type, defined in the Kotlin
standard library.
The coroutine context is a set of various elements. The main elements are the Job of the coroutine, which we've seen
before, and its dispatcher, which is covered in this section.
Dispatchers
and
threads
The coroutine context includes a coroutine dispatcher (see CoroutineDispatcher) that determines what thread or threads
the corresponding coroutine uses for its execution. The coroutine dispatcher can confine coroutine execution to a
specific thread, dispatch it to a thread pool, or let it run unconfined.
All coroutine builders like launch and async accept an optional CoroutineContext parameter that can be used to explicitly
specify the dispatcher for the new coroutine and other context elements.
import kotlinx.coroutines.*
872
You can get the full code here.
When launch { ... } is used without parameters, it inherits the context (and thus dispatcher) from the CoroutineScope it is
being launched from. In this case, it inherits the context of the main runBlocking coroutine which runs in the main thread.
Dispatchers.Unconfined is a special dispatcher that also appears to run in the main thread, but it is, in fact, a different
mechanism that is explained later.
The default dispatcher that is used when no other dispatcher is explicitly specified in the scope. It is represented by
Dispatchers.Default and uses a shared background pool of threads.
newSingleThreadContext creates a thread for the coroutine to run. A dedicated thread is a very expensive resource. In a
real application it must be either released, when no longer needed, using the close function, or stored in a top-level
variable and reused throughout the application.
Unconfined
vs
confined
dispatcher
The Dispatchers.Unconfined coroutine dispatcher starts a coroutine in the caller thread, but only until the first suspension
point. After suspension it resumes the coroutine in the thread that is fully determined by the suspending function that was
invoked. The unconfined dispatcher is appropriate for coroutines which neither consume CPU time nor update any
shared data (like UI) confined to a specific thread.
On the other side, the dispatcher is inherited from the outer CoroutineScope by default. The default dispatcher for the
runBlocking coroutine, in particular, is confined to the invoker thread, so inheriting it has the effect of confining execution
to this thread with predictable FIFO scheduling.
import kotlinx.coroutines.*
873
You can get the full code here.
So, the coroutine with the context inherited from runBlocking {...} continues to execute in the main thread, while the
unconfined one resumes in the default executor thread that the delay function is using.
The unconfined dispatcher is an advanced mechanism that can be helpful in certain corner cases where
dispatching of a coroutine for its execution later is not needed or produces undesirable side-effects, because
some operation in a coroutine must be performed right away. The unconfined dispatcher should not be used in
general code.
Debugging
coroutines
and
threads
Coroutines can suspend on one thread and resume on another thread. Even with a single-threaded dispatcher it might be
hard to figure out what the coroutine was doing, where, and when if you don't have special tooling.
Debugging
with
IDEA
The Coroutine Debugger of the Kotlin plugin simplifies debugging coroutines in IntelliJ IDEA.
The Debug tool window contains the 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.
874
Debugging coroutines
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.
Get a full report that contains the state of each coroutine and its stack. To obtain it, right-click inside the Coroutines
tab, and then click Get Coroutines Dump.
To start coroutine debugging, you just need to set breakpoints and run the application in debug mode.
Debugging
using
logging
Another approach to debugging applications with threads without Coroutine Debugger is to print the thread name in the
log file on each log statement. This feature is universally supported by logging frameworks. When using coroutines, the
thread name alone does not give much of a context, so kotlinx.coroutines includes debugging facilities to make it easier.
import kotlinx.coroutines.*
875
}
log("The answer is ${a.await() * b.await()}")
//sampleEnd
}
There are three coroutines. The main coroutine (#1) inside runBlocking and two coroutines computing the deferred values
a (#2) and b (#3). They are all executing in the context of runBlocking and are confined to the main thread. The output of
this code is:
The log function prints the name of the thread in square brackets, and you can see that it is the main thread with the
identifier of the currently executing coroutine appended to it. This identifier is consecutively assigned to all created
coroutines when the debugging mode is on.
Debugging mode is also turned on when JVM is run with -ea option. You can read more about debugging
facilities in the documentation of the DEBUG_PROPERTY_NAME property.
Jumping
between
threads
Run the following code with the -Dkotlinx.coroutines.debug JVM option (see debug):
import kotlinx.coroutines.*
fun main() {
//sampleStart
newSingleThreadContext("Ctx1").use { ctx1 ->
newSingleThreadContext("Ctx2").use { ctx2 ->
runBlocking(ctx1) {
log("Started in ctx1")
withContext(ctx2) {
log("Working in ctx2")
}
log("Back to ctx1")
}
}
}
//sampleEnd
}
876
You can get the full code here.
It demonstrates several new techniques. One is using runBlocking with an explicitly specified context, and the other one is
using the withContext function to change the context of a coroutine while still staying in the same coroutine, as you can
see in the output below:
Note that this example also uses the use function from the Kotlin standard library to release threads created with
newSingleThreadContext when they are no longer needed.
Job
in
the
context
The coroutine's Job is part of its context, and can be retrieved from it using the coroutineContext[Job] expression:
import kotlinx.coroutines.*
My job is "coroutine#1":BlockingCoroutine{Active}@6d311334
Note that isActive in CoroutineScope is just a convenient shortcut for coroutineContext[Job]?.isActive == true.
Children
of
a
coroutine
When a coroutine is launched in the CoroutineScope of another coroutine, it inherits its context via
CoroutineScope.coroutineContext and the Job of the new coroutine becomes a child of the parent coroutine's job. When
the parent coroutine is cancelled, all its children are recursively cancelled, too.
However, this parent-child relation can be explicitly overriden in one of two ways:
1. When a different scope is explicitly specified when launching a coroutine (for example, GlobalScope.launch), then it
does not inherit a Job from the parent scope.
877
2. When a different Job object is passed as the context for the new coroutine (as show in the example below), then it
overrides the Job of the parent scope.
In both cases, the launched coroutine is not tied to the scope it was launched from and operates independently.
import kotlinx.coroutines.*
Parental
responsibilities
A parent coroutine always waits for completion of all its children. A parent does not have to explicitly track all the children
it launches, and it does not have to use Job.join to wait for them at the end:
import kotlinx.coroutines.*
878
//sampleStart
// launch a coroutine to process some kind of incoming request
val request = launch {
repeat(3) { i -> // launch a few children jobs
launch {
delay((i + 1) * 200L) // variable delay 200ms, 400ms, 600ms
println("Coroutine $i is done")
}
}
println("request: I'm done and I don't explicitly join my children that are still
active")
}
request.join() // wait for completion of the request, including all its children
println("Now processing of the request is complete")
//sampleEnd
}
request: I'm done and I don't explicitly join my children that are still active
Coroutine 0 is done
Coroutine 1 is done
Coroutine 2 is done
Now processing of the request is complete
Naming
coroutines
for
debugging
Automatically assigned ids are good when coroutines log often and you just need to correlate log records coming from
the same coroutine. However, when a coroutine is tied to the processing of a specific request or doing some specific
background task, it is better to name it explicitly for debugging purposes. The CoroutineName context element serves the
same purpose as the thread name. It is included in the thread name that is executing this coroutine when the debugging
mode is turned on.
import kotlinx.coroutines.*
879
val v2 = async(CoroutineName("v2coroutine")) {
delay(1000)
log("Computing v2")
6
}
log("The answer for v1 / v2 = ${v1.await() / v2.await()}")
//sampleEnd
}
Combining
context
elements
Sometimes we need to define multiple elements for a coroutine context. We can use the + operator for that. For example,
we can launch a coroutine with an explicitly specified dispatcher and an explicitly specified name at the same time:
import kotlinx.coroutines.*
The output of this code with the -Dkotlinx.coroutines.debug JVM option is:
Coroutine
scope
Let us put our knowledge about contexts, children and jobs together. Assume that our application has an object with a
880
lifecycle, but that object is not a coroutine. For example, we are writing an Android application and launch various
coroutines in the context of an Android activity to perform asynchronous operations to fetch and update data, do
animations, etc. All of these coroutines must be cancelled when the activity is destroyed to avoid memory leaks. We, of
course, can manipulate contexts and jobs manually to tie the lifecycles of the activity and its coroutines, but
kotlinx.coroutines provides an abstraction encapsulating that: CoroutineScope. You should be already familiar with the
coroutine scope as all coroutine builders are declared as extensions on it.
We manage the lifecycles of our coroutines by creating an instance of CoroutineScope tied to the lifecycle of our activity.
A CoroutineScope instance can be created by the CoroutineScope() or MainScope() factory functions. The former creates
a general-purpose scope, while the latter creates a scope for UI applications and uses Dispatchers.Main as the default
dispatcher:
class Activity {
private val mainScope = MainScope()
fun destroy() {
mainScope.cancel()
}
// to be continued ...
Now, we can launch coroutines in the scope of this Activity using the defined scope. For the demo, we launch ten
coroutines that delay for a different time:
In our main function we create the activity, call our test doSomething function, and destroy the activity after 500ms. This
cancels all the coroutines that were launched from doSomething. We can see that because after the destruction of the
activity no more messages are printed, even if we wait a little longer.
import kotlinx.coroutines.*
class Activity {
private val mainScope = CoroutineScope(Dispatchers.Default) // use Default for test purposes
fun destroy() {
mainScope.cancel()
}
fun doSomething() {
// launch ten coroutines for a demo, each working for a different time
repeat(10) { i ->
mainScope.launch {
881
delay((i + 1) * 200L) // variable delay 200ms, 400ms, ... etc
println("Coroutine $i is done")
}
}
}
} // class Activity ends
Launched coroutines
Coroutine 0 is done
Coroutine 1 is done
Destroying activity!
As you can see, only the first two coroutines print a message and the others are cancelled by a single invocation of
job.cancel() in Activity.destroy().
Note, that Android has first-party support for coroutine scope in all entities with the lifecycle. See the
corresponding documentation.
Thread-local
data
Sometimes it is convenient to have an ability to pass some thread-local data to or between coroutines. However, since
they are not bound to any particular thread, this will likely lead to boilerplate if done manually.
For ThreadLocal, the asContextElement extension function is here for the rescue. It creates an additional context element
which keeps the value of the given ThreadLocal and restores it every time the coroutine switches its context.
import kotlinx.coroutines.*
882
fun main() = runBlocking<Unit> {
//sampleStart
threadLocal.set("main")
println("Pre-main, current thread: ${Thread.currentThread()}, thread local value:
'${threadLocal.get()}'")
val job = launch(Dispatchers.Default + threadLocal.asContextElement(value = "launch")) {
println("Launch start, current thread: ${Thread.currentThread()}, thread local value:
'${threadLocal.get()}'")
yield()
println("After yield, current thread: ${Thread.currentThread()}, thread local value:
'${threadLocal.get()}'")
}
job.join()
println("Post-main, current thread: ${Thread.currentThread()}, thread local value:
'${threadLocal.get()}'")
//sampleEnd
}
In this example we launch a new coroutine in a background thread pool using Dispatchers.Default, so it works on a
different thread from the thread pool, but it still has the value of the thread local variable that we specified using
threadLocal.asContextElement(value = "launch"), no matter which thread the coroutine is executed on. Thus, the output
(with debug) is:
It's easy to forget to set the corresponding context element. The thread-local variable accessed from the coroutine may
then have an unexpected value, if the thread running the coroutine is different. To avoid such situations, it is
recommended to use the ensurePresent method and fail-fast on improper usages.
ThreadLocal has first-class support and can be used with any primitive kotlinx.coroutines provides. It has one key
limitation, though: when a thread-local is mutated, a new value is not propagated to the coroutine caller (because a
context element cannot track all ThreadLocal object accesses), and the updated value is lost on the next suspension. Use
withContext to update the value of the thread-local in a coroutine, see asContextElement for more details.
Alternatively, a value can be stored in a mutable box like class Counter(var i: Int), which is, in turn, stored in a thread-local
variable. However, in this case you are fully responsible to synchronize potentially concurrent modifications to the variable
in this mutable box.
For advanced usage, for example for integration with logging MDC, transactional contexts or any other libraries which
internally use thread-locals for passing data, see the documentation of the ThreadContextElement interface that should
be implemented.
883
Asynchronous
Flow
A suspending function asynchronously returns a single value, but how can we return multiple asynchronously computed
values? This is where Kotlin Flows come in.
Representing
multiple
values
Multiple values can be represented in Kotlin using collections. For example, we can have a simple function that returns a
List of three numbers and then print them all using forEach:
1
2
3
Sequences
If we are computing the numbers with some CPU-consuming blocking code (each computation taking 100ms), then we
can represent the numbers using a Sequence:
fun main() {
simple().forEach { value -> println(value) }
}
884
This code outputs the same numbers, but it waits 100ms before printing each one.
Suspending
functions
However, this computation blocks the main thread that is running the code. When these values are computed by
asynchronous code we can mark the simple function with a suspend modifier, so that it can perform its work without
blocking and return the result as a list:
import kotlinx.coroutines.*
//sampleStart
suspend fun simple(): List<Int> {
delay(1000) // pretend we are doing something asynchronous here
return listOf(1, 2, 3)
}
Flows
Using the List<Int> result type, means we can only return all the values at once. To represent the stream of values that are
being asynchronously computed, we can use a Flow<Int> type just like we would use the Sequence<Int> type for
synchronously computed values:
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
//sampleStart
fun simple(): Flow<Int> = flow { // flow builder
for (i in 1..3) {
delay(100) // pretend we are doing something useful here
emit(i) // emit next value
}
}
885
simple().collect { value -> println(value) }
}
//sampleEnd
This code waits 100ms before printing each number without blocking the main thread. This is verified by printing "I'm not
blocked" every 100ms from a separate coroutine that is running in the main thread:
Notice the following differences in the code with the Flow from the earlier examples:
We can replace delay with Thread.sleep in the body of simple 's flow { ... } and see that the main thread is
blocked in this case.
Flows
are
cold
Flows are cold streams similar to sequences — the code inside a flow builder does not run until the flow is collected.
This becomes clear in the following example:
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
//sampleStart
fun simple(): Flow<Int> = flow {
println("Flow started")
for (i in 1..3) {
delay(100)
emit(i)
}
}
886
fun main() = runBlocking<Unit> {
println("Calling simple function...")
val flow = simple()
println("Calling collect...")
flow.collect { value -> println(value) }
println("Calling collect again...")
flow.collect { value -> println(value) }
}
//sampleEnd
Which prints:
This is a key reason the simple function (which returns a flow) is not marked with suspend modifier. By itself, simple() call
returns quickly and does not wait for anything. The flow starts every time it is collected, that is why we see "Flow started"
when we call collect again.
Flow
cancellation
basics
Flow adheres to the general cooperative cancellation of coroutines. As usual, flow collection can be cancelled when the
flow is suspended in a cancellable suspending function (like delay). The following example shows how the flow gets
cancelled on a timeout when running in a withTimeoutOrNull block and stops executing its code:
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
//sampleStart
fun simple(): Flow<Int> = flow {
for (i in 1..3) {
delay(100)
println("Emitting $i")
emit(i)
}
}
887
withTimeoutOrNull(250) { // Timeout after 250ms
simple().collect { value -> println(value) }
}
println("Done")
}
//sampleEnd
Notice how only two numbers get emitted by the flow in the simple function, producing the following output:
Emitting 1
1
Emitting 2
2
Done
Flow
builders
The flow { ... } builder from the previous examples is the most basic one. There are other builders for easier declaration of
flows:
Various collections and sequences can be converted to flows using .asFlow() extension functions.
So, the example that prints the numbers from 1 to 3 from a flow can be written as:
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
Intermediate
flow
operators
888
Flows can be transformed with operators, just as you would with collections and sequences. Intermediate operators are
applied to an upstream flow and return a downstream flow. These operators are cold, just like flows are. A call to such an
operator is not a suspending function itself. It works quickly, returning the definition of a new transformed flow.
The basic operators have familiar names like map and filter. The important difference to sequences is that blocks of code
inside these operators can call suspending functions.
For example, a flow of incoming requests can be mapped to the results with the map operator, even when performing a
request is a long-running operation that is implemented by a suspending function:
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
//sampleStart
suspend fun performRequest(request: Int): String {
delay(1000) // imitate long-running asynchronous work
return "response $request"
}
It produces the following three lines, each line appearing after each second:
response 1
response 2
response 3
Transform
operator
Among the flow transformation operators, the most general one is called transform. It can be used to imitate simple
transformations like map and filter, as well as implement more complex transformations. Using the transform operator, we
can emit arbitrary values an arbitrary number of times.
For example, using transform we can emit a string before performing a long-running asynchronous request and follow it
with a response:
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
889
}
Making request 1
response 1
Making request 2
response 2
Making request 3
response 3
Size-limiting
operators
Size-limiting intermediate operators like take cancel the execution of the flow when the corresponding limit is reached.
Cancellation in coroutines is always performed by throwing an exception, so that all the resource-management functions
(like try { ... } finally { ... } blocks) operate normally in case of cancellation:
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
//sampleStart
fun numbers(): Flow<Int> = flow {
try {
emit(1)
emit(2)
println("This line will not execute")
emit(3)
} finally {
println("Finally in numbers")
}
}
890
You can get the full code from here.
The output of this code clearly shows that the execution of the flow { ... } body in the numbers() function stopped after
emitting the second number:
1
2
Finally in numbers
Terminal
flow
operators
Terminal operators on flows are suspending functions that start a collection of the flow. The collect operator is the most
basic one, but there are other terminal operators, which can make it easier:
Operators to get the first value and to ensure that a flow emits a single value.
For example:
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
55
Flows
are
sequential
Each individual collection of a flow is performed sequentially unless special operators that operate on multiple flows are
891
used. The collection works directly in the coroutine that calls a terminal operator. No new coroutines are launched by
default. Each emitted value is processed by all the intermediate operators from upstream to downstream and is then
delivered to the terminal operator after.
See the following example that filters the even integers and maps them to strings:
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
Producing:
Filter 1
Filter 2
Map 2
Collect string 2
Filter 3
Filter 4
Map 4
Collect string 4
Filter 5
Flow
context
Collection of a flow always happens in the context of the calling coroutine. For example, if there is a simple flow, then the
following code runs in the context specified by the author of this code, regardless of the implementation details of the
simple flow:
withContext(context) {
simple().collect { value ->
println(value) // run in the specified context
}
892
}
So, by default, code in the flow { ... } builder runs in the context that is provided by a collector of the corresponding flow.
For example, consider the implementation of a simple function that prints the thread it is called on and emits three
numbers:
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
Since simple().collect is called from the main thread, the body of simple 's flow is also called in the main thread. This is
the perfect default for fast-running or asynchronous code that does not care about the execution context and does not
block the caller.
Wrong
emission
withContext
However, the long-running CPU-consuming code might need to be executed in the context of Dispatchers.Default and UI-
updating code might need to be executed in the context of Dispatchers.Main. Usually, withContext is used to change the
context in the code using Kotlin coroutines, but code in the flow { ... } builder has to honor the context preservation
property and is not allowed to emit from a different context.
893
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
//sampleStart
fun simple(): Flow<Int> = flow {
// The WRONG way to change context for CPU-consuming code in flow builder
kotlinx.coroutines.withContext(Dispatchers.Default) {
for (i in 1..3) {
Thread.sleep(100) // pretend we are computing it in CPU-consuming way
emit(i) // emit next value
}
}
}
flowOn
operator
The exception refers to the flowOn function that shall be used to change the context of the flow emission. The correct way
to change the context of a flow is shown in the example below, which also prints the names of the corresponding threads
to show how it all works:
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
894
fun main() = runBlocking<Unit> {
simple().collect { value ->
log("Collected $value")
}
}
//sampleEnd
Notice how flow { ... } works in the background thread, while collection happens in the main thread:
Another thing to observe here is that the flowOn operator has changed the default sequential nature of the flow. Now
collection happens in one coroutine ("coroutine#1") and emission happens in another coroutine ("coroutine#2") that is
running in another thread concurrently with the collecting coroutine. The flowOn operator creates another coroutine for an
upstream flow when it has to change the CoroutineDispatcher in its context.
Buffering
Running different parts of a flow in different coroutines can be helpful from the standpoint of the overall time it takes to
collect the flow, especially when long-running asynchronous operations are involved. For example, consider a case when
the emission by a simple flow is slow, taking 100 ms to produce an element; and collector is also slow, taking 300 ms to
process an element. Let's see how long it takes to collect such a flow with three numbers:
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
import kotlin.system.*
//sampleStart
fun simple(): Flow<Int> = flow {
for (i in 1..3) {
delay(100) // pretend we are asynchronously waiting 100 ms
emit(i) // emit next value
}
}
895
You can get the full code from here.
It produces something like this, with the whole collection taking around 1200 ms (three numbers, 400 ms for each):
1
2
3
Collected in 1220 ms
We can use a buffer operator on a flow to run emitting code of the simple flow concurrently with collecting code, as
opposed to running them sequentially:
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
import kotlin.system.*
It produces the same numbers just faster, as we have effectively created a processing pipeline, having to only wait 100
ms for the first number and then spending only 300 ms to process each number. This way it takes around 1000 ms to run:
1
2
3
Collected in 1071 ms
896
Note that the flowOn operator uses the same buffering mechanism when it has to change a
CoroutineDispatcher, but here we explicitly request buffering without changing the execution context.
Conflation
When a flow represents partial results of the operation or operation status updates, it may not be necessary to process
each value, but instead, only most recent ones. In this case, the conflate operator can be used to skip intermediate values
when a collector is too slow to process them. Building on the previous example:
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
import kotlin.system.*
We see that while the first number was still being processed the second, and third were already produced, so the second
one was conflated and only the most recent (the third one) was delivered to the collector:
1
3
Collected in 758 ms
Processing
the
latest
value
Conflation is one way to speed up processing when both the emitter and collector are slow. It does it by dropping emitted
values. The other way is to cancel a slow collector and restart it every time a new value is emitted. There is a family of
xxxLatest operators that perform the same essential logic of a xxx operator, but cancel the code in their block on a new
897
value. Let's try changing conflate to collectLatest in the previous example:
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
import kotlin.system.*
Since the body of collectLatest takes 300 ms, but new values are emitted every 100 ms, we see that the block is run on
every value, but completes only for the last value:
Collecting 1
Collecting 2
Collecting 3
Done 3
Collected in 741 ms
Composing
multiple
flows
There are lots of ways to compose multiple flows.
Zip
Just like the Sequence.zip extension function in the Kotlin standard library, flows have a zip operator that combines the
corresponding values of two flows:
import kotlinx.coroutines.*
898
import kotlinx.coroutines.flow.*
1 -> one
2 -> two
3 -> three
Combine
When flow represents the most recent value of a variable or operation (see also the related section on conflation), it might
be needed to perform a computation that depends on the most recent values of the corresponding flows and to
recompute it whenever any of the upstream flows emit a value. The corresponding family of operators is called combine.
For example, if the numbers in the previous example update every 300ms, but strings update every 400 ms, then zipping
them using the zip operator will still produce the same result, albeit results that are printed every 400 ms:
We use a onEach intermediate operator in this example to delay each element and make the code that emits
sample flows more declarative and shorter.
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
899
You can get the full code from here.
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
We get quite a different output, where a line is printed at each emission from either nums or strs flows:
Flattening
flows
Flows represent asynchronously received sequences of values, so it is quite easy to get in a situation where each value
triggers a request for another sequence of values. For example, we can have the following function that returns a flow of
two strings 500 ms apart:
Now if we have a flow of three integers and call requestFlow for each of them like this:
(1..3).asFlow().map { requestFlow(it) }
900
Then we end up with a flow of flows (Flow<Flow<String>>) that needs to be flattened into a single flow for further
processing. Collections and sequences have flatten and flatMap operators for this. However, due to the asynchronous
nature of flows they call for different modes of flattening, as such, there is a family of flattening operators on flows.
flatMapConcat
Concatenating mode is implemented by flatMapConcat and flattenConcat operators. They are the most direct analogues
of the corresponding sequence operators. They wait for the inner flow to complete before starting to collect the next one
as the following example shows:
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
flatMapMerge
Another flattening mode is to concurrently collect all the incoming flows and merge their values into a single flow so that
values are emitted as soon as possible. It is implemented by flatMapMerge and flattenMerge operators. They both accept
an optional concurrency parameter that limits the number of concurrent flows that are collected at the same time (it is
equal to DEFAULT_CONCURRENCY by default).
901
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
Note that the flatMapMerge calls its block of code ({ requestFlow(it) } in this example) sequentially, but collects
the resulting flows concurrently, it is the equivalent of performing a sequential map { requestFlow(it) } first and
then calling flattenMerge on the result.
flatMapLatest
In a similar way to the collectLatest operator, that was shown in "Processing the latest value" section, there is the
corresponding "Latest" flattening mode where a collection of the previous flow is cancelled as soon as new flow is
emitted. It is implemented by the flatMapLatest operator.
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
902
}
The output here in this example is a good demonstration of how flatMapLatest works:
Note that flatMapLatest cancels all the code in its block ({ requestFlow(it) } in this example) on a new value. It
makes no difference in this particular example, because the call to requestFlow itself is fast, not-suspending,
and cannot be cancelled. However, it would show up if we were to use suspending functions like delay in there.
Flow
exceptions
Flow collection can complete with an exception when an emitter or code inside the operators throw an exception. There
are several ways to handle these exceptions.
Collector
try
and
catch
A collector can use Kotlin's try/catch block to handle exceptions:
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
//sampleStart
fun simple(): Flow<Int> = flow {
for (i in 1..3) {
println("Emitting $i")
emit(i) // emit next value
}
}
903
try {
simple().collect { value ->
println(value)
check(value <= 1) { "Collected $value" }
}
} catch (e: Throwable) {
println("Caught $e")
}
}
//sampleEnd
This code successfully catches an exception in collect terminal operator and, as we see, no more values are emitted after
that:
Emitting 1
1
Emitting 2
2
Caught java.lang.IllegalStateException: Collected 2
Everything
is
caught
The previous example actually catches any exception happening in the emitter or in any intermediate or terminal
operators. For example, let's change the code so that emitted values are mapped to strings, but the corresponding code
produces an exception:
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
//sampleStart
fun simple(): Flow<String> =
flow {
for (i in 1..3) {
println("Emitting $i")
emit(i) // emit next value
}
}
.map { value ->
check(value <= 1) { "Crashed on $value" }
"string $value"
}
904
You can get the full code from here.
Emitting 1
string 1
Emitting 2
Caught java.lang.IllegalStateException: Crashed on 2
Exception
transparency
But how can code of the emitter encapsulate its exception handling behavior?
Flows must be transparent to exceptions and it is a violation of the exception transparency to emit values in the flow { ... }
builder from inside of a try/catch block. This guarantees that a collector throwing an exception can always catch it using
try/catch as in the previous example.
The emitter can use a catch operator that preserves this exception transparency and allows encapsulation of its
exception handling. The body of the catch operator can analyze an exception and react to it in different ways depending
on which exception was caught:
Exceptions can be turned into emission of values using emit from the body of catch.
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
905
.collect { value -> println(value) }
//sampleEnd
}
The output of the example is the same, even though we do not have try/catch around the code anymore.
Transparent
catch
The catch intermediate operator, honoring exception transparency, catches only upstream exceptions (that is an
exception from all the operators above catch, but not below it). If the block in collect { ... } (placed below catch) throws an
exception then it escapes:
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
//sampleStart
fun simple(): Flow<Int> = flow {
for (i in 1..3) {
println("Emitting $i")
emit(i)
}
}
A "Caught ..." message is not printed despite there being a catch operator:
Emitting 1
1
Emitting 2
Exception in thread "main" java.lang.IllegalStateException: Collected 2
at ...
Catching
declaratively
906
We can combine the declarative nature of the catch operator with a desire to handle all the exceptions, by moving the
body of the collect operator into onEach and putting it before the catch operator. Collection of this flow must be triggered
by a call to collect() without parameters:
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
Now we can see that a "Caught ..." message is printed and so we can catch all the exceptions without explicitly using a
try/catch block:
Emitting 1
1
Emitting 2
Caught java.lang.IllegalStateException: Collected 2
Flow
completion
When flow collection completes (normally or exceptionally) it may need to execute an action. As you may have already
noticed, it can be done in two ways: imperative or declarative.
Imperative
finally
block
In addition to try/ catch, a collector can also use a finally block to execute an action upon collect completion.
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
907
//sampleStart
fun simple(): Flow<Int> = (1..3).asFlow()
This code prints three numbers produced by the simple flow followed by a "Done" string:
1
2
3
Done
Declarative
handling
For the declarative approach, flow has onCompletion intermediate operator that is invoked when the flow has completely
collected.
The previous example can be rewritten using an onCompletion operator and produces the same output:
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
The key advantage of onCompletion is a nullable Throwable parameter of the lambda that can be used to determine
whether the flow collection was completed normally or exceptionally. In the following example the simple flow throws an
exception after emitting the number 1:
908
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
//sampleStart
fun simple(): Flow<Int> = flow {
emit(1)
throw RuntimeException()
}
1
Flow completed exceptionally
Caught exception
The onCompletion operator, unlike catch, does not handle the exception. As we can see from the above example code,
the exception still flows downstream. It will be delivered to further onCompletion operators and can be handled with a
catch operator.
Successful
completion
Another difference with catch operator is that onCompletion sees all exceptions and receives a null exception only on
successful completion of the upstream flow (without cancellation or failure).
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
//sampleStart
fun simple(): Flow<Int> = (1..3).asFlow()
909
You can get the full code from here.
We can see the completion cause is not null, because the flow was aborted due to downstream exception:
1
Flow completed with java.lang.IllegalStateException: Collected 2
Exception in thread "main" java.lang.IllegalStateException: Collected 2
Imperative
versus
declarative
Now we know how to collect flow, and handle its completion and exceptions in both imperative and declarative ways. The
natural question here is, which approach is preferred and why? As a library, we do not advocate for any particular
approach and believe that both options are valid and should be selected according to your own preferences and code
style.
Launching
flow
It is easy to use flows to represent asynchronous events that are coming from some source. In this case, we need an
analogue of the addEventListener function that registers a piece of code with a reaction for incoming events and
continues further work. The onEach operator can serve this role. However, onEach is an intermediate operator. We also
need a terminal operator to collect the flow. Otherwise, just calling onEach has no effect.
If we use the collect terminal operator after onEach, then the code after it will wait until the flow is collected:
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
//sampleStart
// Imitate a flow of events
fun events(): Flow<Int> = (1..3).asFlow().onEach { delay(100) }
910
Event: 1
Event: 2
Event: 3
Done
The launchIn terminal operator comes in handy here. By replacing collect with launchIn we can launch a collection of the
flow in a separate coroutine, so that execution of further code immediately continues:
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
//sampleStart
fun main() = runBlocking<Unit> {
events()
.onEach { event -> println("Event: $event") }
.launchIn(this) // <--- Launching the flow in a separate coroutine
println("Done")
}
//sampleEnd
It prints:
Done
Event: 1
Event: 2
Event: 3
The required parameter to launchIn must specify a CoroutineScope in which the coroutine to collect the flow is launched.
In the above example this scope comes from the runBlocking coroutine builder, so while the flow is running, this
runBlocking scope waits for completion of its child coroutine and keeps the main function from returning and terminating
this example.
In actual applications a scope will come from an entity with a limited lifetime. As soon as the lifetime of this entity is
terminated the corresponding scope is cancelled, cancelling the collection of the corresponding flow. This way the pair of
onEach { ... }.launchIn(scope) works like the addEventListener. However, there is no need for the corresponding
removeEventListener function, as cancellation and structured concurrency serve this purpose.
Note that launchIn also returns a Job, which can be used to cancel the corresponding flow collection coroutine only
without cancelling the whole scope or to join it.
Flow
cancellation
checks
For convenience, the flow builder performs additional ensureActive checks for cancellation on each emitted value. It
911
means that a busy loop emitting from a flow { ... } is cancellable:
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
//sampleStart
fun foo(): Flow<Int> = flow {
for (i in 1..5) {
println("Emitting $i")
emit(i)
}
}
Emitting 1
1
Emitting 2
2
Emitting 3
3
Emitting 4
Exception in thread "main" kotlinx.coroutines.JobCancellationException: BlockingCoroutine was
cancelled; job="coroutine#1":BlockingCoroutine{Cancelled}@6d7b4f4c
However, most other flow operators do not do additional cancellation checks on their own for performance reasons. For
example, if you use IntRange.asFlow extension to write the same busy loop and don't suspend anywhere, then there are
no checks for cancellation:
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
//sampleStart
fun main() = runBlocking<Unit> {
(1..5).asFlow().collect { value ->
if (value == 3) cancel()
println(value)
}
}
//sampleEnd
912
You can get the full code from here.
All numbers from 1 to 5 are collected and cancellation gets detected only before return from runBlocking:
1
2
3
4
5
Exception in thread "main" kotlinx.coroutines.JobCancellationException: BlockingCoroutine was
cancelled; job="coroutine#1":BlockingCoroutine{Cancelled}@3327bd23
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
//sampleStart
fun main() = runBlocking<Unit> {
(1..5).asFlow().cancellable().collect { value ->
if (value == 3) cancel()
println(value)
}
}
//sampleEnd
With the cancellable operator only the numbers from 1 to 3 are collected:
1
2
3
Exception in thread "main" kotlinx.coroutines.JobCancellationException: BlockingCoroutine was
cancelled; job="coroutine#1":BlockingCoroutine{Cancelled}@5ec0a365
Flow
and
Reactive
Streams
For those who are familiar with Reactive Streams or reactive frameworks such as RxJava and project Reactor, design of
the Flow may look very familiar.
Indeed, its design was inspired by Reactive Streams and its various implementations. But Flow main goal is to have as
913
simple design as possible, be Kotlin and suspension friendly and respect structured concurrency. Achieving this goal
would be impossible without reactive pioneers and their tremendous work. You can read the complete story in Reactive
Streams and Kotlin Flows article.
While being different, conceptually, Flow is a reactive stream and it is possible to convert it to the reactive (spec and TCK
compliant) Publisher and vice versa. Such converters are provided by kotlinx.coroutines out-of-the-box and can be found
in corresponding reactive modules (kotlinx-coroutines-reactive for Reactive Streams, kotlinx-coroutines-reactor for
Project Reactor and kotlinx-coroutines-rx2/ kotlinx-coroutines-rx3 for RxJava2/RxJava3). Integration modules include
conversions from and to Flow, integration with Reactor's Context and suspension-friendly ways to work with various
reactive entities.
Channels
Deferred values provide a convenient way to transfer a single value between coroutines. Channels provide a way to
transfer a stream of values.
Channel
basics
A Channel is conceptually very similar to BlockingQueue. One key difference is that instead of a blocking put operation it
has a suspending send, and instead of a blocking take operation it has a suspending receive.
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*
1
4
9
914
16
25
Done!
Closing
and
iteration
over
channels
Unlike a queue, a channel can be closed to indicate that no more elements are coming. On the receiver side it is
convenient to use a regular for loop to receive elements from the channel.
Conceptually, a close is like sending a special close token to the channel. The iteration stops as soon as this close token
is received, so there is a guarantee that all previously sent elements before the close are received:
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*
Building
channel
producers
The pattern where a coroutine is producing a sequence of elements is quite common. This is a part of producer-
consumer pattern that is often found in concurrent code. You could abstract such a producer into a function that takes
channel as its parameter, but this goes contrary to common sense that results must be returned from functions.
There is a convenient coroutine builder named produce that makes it easy to do it right on producer side, and an
extension function consumeEach, that replaces a for loop on the consumer side:
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*
915
val squares = produceSquares()
squares.consumeEach { println(it) }
println("Done!")
//sampleEnd
}
Pipelines
A pipeline is a pattern where one coroutine is producing, possibly infinite, stream of values:
And another coroutine or coroutines are consuming that stream, doing some processing, and producing some other
results. In the example below, the numbers are just squared:
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*
916
You can get the full code here.
All functions that create coroutines are defined as extensions on CoroutineScope, so that we can rely on
structured concurrency to make sure that we don't have lingering global coroutines in our application.
Prime
numbers
with
pipeline
Let's take pipelines to the extreme with an example that generates prime numbers using a pipeline of coroutines. We start
with an infinite sequence of numbers.
The following pipeline stage filters an incoming stream of numbers, removing all the numbers that are divisible by the
given prime number:
Now we build our pipeline by starting a stream of numbers from 2, taking a prime number from the current channel, and
launching new pipeline stage for each prime number found:
numbersFrom(2) -> filter(2) -> filter(3) -> filter(5) -> filter(7) ...
The following example prints the first ten prime numbers, running the whole pipeline in the context of the main thread.
Since all the coroutines are launched in the scope of the main runBlocking coroutine we don't have to keep an explicit list
of all the coroutines we have started. We use cancelChildren extension function to cancel all the children coroutines after
we have printed the first ten prime numbers.
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*
917
fun CoroutineScope.numbersFrom(start: Int) = produce<Int> {
var x = start
while (true) send(x++) // infinite stream of integers from start
}
2
3
5
7
11
13
17
19
23
29
Note that you can build the same pipeline using iterator coroutine builder from the standard library. Replace produce with
iterator, send with yield, receive with next, ReceiveChannel with Iterator, and get rid of the coroutine scope. You will not
need runBlocking either. However, the benefit of a pipeline that uses channels as shown above is that it can actually use
multiple CPU cores if you run it in Dispatchers.Default context.
Anyway, this is an extremely impractical way to find prime numbers. In practice, pipelines do involve some other
suspending invocations (like asynchronous calls to remote services) and these pipelines cannot be built using sequence/
iterator, because they do not allow arbitrary suspension, unlike produce, which is fully asynchronous.
Fan-out
Multiple coroutines may receive from the same channel, distributing work between themselves. Let us start with a
producer coroutine that is periodically producing integers (ten numbers per second):
Then we can have several processor coroutines. In this example, they just print their id and received number:
918
fun CoroutineScope.launchProcessor(id: Int, channel: ReceiveChannel<Int>) = launch {
for (msg in channel) {
println("Processor #$id received $msg")
}
}
Now let us launch five processors and let them work for almost a second. See what happens:
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*
The output will be similar to the the following one, albeit the processor ids that receive each specific integer may be
different:
Processor #2 received 1
Processor #4 received 2
Processor #0 received 3
Processor #1 received 4
Processor #3 received 5
Processor #2 received 6
Processor #4 received 7
Processor #0 received 8
Processor #1 received 9
Processor #3 received 10
Note that cancelling a producer coroutine closes its channel, thus eventually terminating iteration over the channel that
919
processor coroutines are doing.
Also, pay attention to how we explicitly iterate over channel with for loop to perform fan-out in launchProcessor code.
Unlike consumeEach, this for loop pattern is perfectly safe to use from multiple coroutines. If one of the processor
coroutines fails, then others would still be processing the channel, while a processor that is written via consumeEach
always consumes (cancels) the underlying channel on its normal or abnormal completion.
Fan-in
Multiple coroutines may send to the same channel. For example, let us have a channel of strings, and a suspending
function that repeatedly sends a specified string to this channel with a specified delay:
Now, let us see what happens if we launch a couple of coroutines sending strings (in this example we launch them in the
context of the main thread as main coroutine's children):
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*
920
foo
foo
BAR!
foo
foo
BAR!
Buffered
channels
The channels shown so far had no buffer. Unbuffered channels transfer elements when sender and receiver meet each
other (aka rendezvous). If send is invoked first, then it is suspended until receive is invoked, if receive is invoked first, it is
suspended until send is invoked.
Both Channel() factory function and produce builder take an optional capacity parameter to specify buffer size. Buffer
allows senders to send multiple elements before suspending, similar to the BlockingQueue with a specified capacity,
which blocks when buffer is full.
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*
It prints "sending" five times using a buffered channel with capacity of four:
Sending 0
Sending 1
Sending 2
Sending 3
Sending 4
The first four elements are added to the buffer and the sender suspends when trying to send the fifth one.
921
Channels
are
fair
Send and receive operations to channels are fair with respect to the order of their invocation from multiple coroutines.
They are served in first-in first-out order, e.g. the first coroutine to invoke receive gets the element. In the following
example two coroutines "ping" and "pong" are receiving the "ball" object from the shared "table" channel.
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*
//sampleStart
data class Ball(var hits: Int)
The "ping" coroutine is started first, so it is the first one to receive the ball. Even though "ping" coroutine immediately
starts receiving the ball again after sending it back to the table, the ball gets received by the "pong" coroutine, because it
was already waiting for it:
ping Ball(hits=1)
pong Ball(hits=2)
ping Ball(hits=3)
pong Ball(hits=4)
Note that sometimes channels may produce executions that look unfair due to the nature of the executor that is being
used. See this issue for details.
Ticker
channels
Ticker channel is a special rendezvous channel that produces Unit every time given delay passes since last consumption
922
from this channel. Though it may seem to be useless standalone, it is a useful building block to create complex time-
based produce pipelines and operators that do windowing and other time-dependent processing. Ticker channel can be
used in select to perform "on tick" action.
To create such channel use a factory method ticker. To indicate that no further elements are needed use
ReceiveChannel.cancel method on it.
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*
Note that ticker is aware of possible consumer pauses and, by default, adjusts next produced element delay if a pause
occurs, trying to maintain a fixed rate of produced elements.
923
Optionally, a mode parameter equal to TickerMode.FIXED_DELAY can be specified to maintain a fixed delay between
elements.
Coroutine
exceptions
handling
This section covers exception handling and cancellation on exceptions. We already know that a cancelled coroutine
throws CancellationException in suspension points and that it is ignored by the coroutines' machinery. Here we look at
what happens if an exception is thrown during cancellation or multiple children of the same coroutine throw an exception.
Exception
propagation
Coroutine builders come in two flavors: propagating exceptions automatically (launch and actor) or exposing them to
users (async and produce). When these builders are used to create a root coroutine, that is not a child of another
coroutine, the former builders treat exceptions as uncaught exceptions, similar to Java's
Thread.uncaughtExceptionHandler, while the latter are relying on the user to consume the final exception, for example via
await or receive (produce and receive are covered later in Channels section).
It can be demonstrated by a simple example that creates root coroutines using the GlobalScope:
GlobalScope is a delicate API that can backfire in non-trivial ways. Creating a root coroutine for the whole
application is one of the rare legitimate uses for GlobalScope, so you must explicitly opt-in into using
GlobalScope with @OptIn(DelicateCoroutinesApi::class).
import kotlinx.coroutines.*
@OptIn(DelicateCoroutinesApi::class)
fun main() = runBlocking {
val job = GlobalScope.launch { // root coroutine with launch
println("Throwing exception from launch")
throw IndexOutOfBoundsException() // Will be printed to the console by
Thread.defaultUncaughtExceptionHandler
}
job.join()
println("Joined failed job")
val deferred = GlobalScope.async { // root coroutine with async
println("Throwing exception from async")
throw ArithmeticException() // Nothing is printed, relying on user to call await
}
try {
deferred.await()
println("Unreached")
} catch (e: ArithmeticException) {
println("Caught ArithmeticException")
}
}
924
You can get the full code here.
CoroutineExceptionHandler
It is possible to customize the default behavior of printing uncaught exceptions to the console.
CoroutineExceptionHandler context element on a root coroutine can be used as generic catch block for this root
coroutine and all its children where custom exception handling may take place. It is similar to
Thread.uncaughtExceptionHandler. You cannot recover from the exception in the CoroutineExceptionHandler. The
coroutine had already completed with the corresponding exception when the handler is called. Normally, the handler is
used to log the exception, show some kind of error message, terminate, and/or restart the application.
On JVM it is possible to redefine global exception handler for all coroutines by registering CoroutineExceptionHandler via
ServiceLoader. Global exception handler is similar to Thread.defaultUncaughtExceptionHandler which is used when no
more specific handlers are registered. On Android, uncaughtExceptionPreHandler is installed as a global coroutine
exception handler.
CoroutineExceptionHandler is invoked only on uncaught exceptions — exceptions that were not handled in any other
way. In particular, all children coroutines (coroutines created in the context of another Job) delegate handling of their
exceptions to their parent coroutine, which also delegates to the parent, and so on until the root, so the
CoroutineExceptionHandler installed in their context is never used. In addition to that, async builder always catches all
exceptions and represents them in the resulting Deferred object, so its CoroutineExceptionHandler has no effect either.
Coroutines running in supervision scope do not propagate exceptions to their parent and are excluded from
this rule. A further Supervision section of this document gives more details.
import kotlinx.coroutines.*
@OptIn(DelicateCoroutinesApi::class)
fun main() = runBlocking {
//sampleStart
val handler = CoroutineExceptionHandler { _, exception ->
println("CoroutineExceptionHandler got $exception")
}
val job = GlobalScope.launch(handler) { // root coroutine, running in GlobalScope
throw AssertionError()
}
val deferred = GlobalScope.async(handler) { // also root, but async instead of launch
925
throw ArithmeticException() // Nothing will be printed, relying on user to call
deferred.await()
}
joinAll(job, deferred)
//sampleEnd
}
Cancellation
and
exceptions
Cancellation is closely related to exceptions. Coroutines internally use CancellationException for cancellation, these
exceptions are ignored by all handlers, so they should be used only as the source of additional debug information, which
can be obtained by catch block. When a coroutine is cancelled using Job.cancel, it terminates, but it does not cancel its
parent.
import kotlinx.coroutines.*
926
Cancelling child
Child is cancelled
Parent is not cancelled
If a coroutine encounters an exception other than CancellationException, it cancels its parent with that exception. This
behaviour cannot be overridden and is used to provide stable coroutines hierarchies for structured concurrency.
CoroutineExceptionHandler implementation is not used for child coroutines.
The original exception is handled by the parent only when all its children terminate, which is demonstrated by the
following example.
import kotlinx.coroutines.*
@OptIn(DelicateCoroutinesApi::class)
fun main() = runBlocking {
//sampleStart
val handler = CoroutineExceptionHandler { _, exception ->
println("CoroutineExceptionHandler got $exception")
}
val job = GlobalScope.launch(handler) {
launch { // the first child
try {
delay(Long.MAX_VALUE)
} finally {
withContext(NonCancellable) {
println("Children are cancelled, but exception is not handled until all
children terminate")
delay(100)
println("The first child finished its non cancellable block")
}
}
}
launch { // the second child
delay(10)
println("Second child throws an exception")
throw ArithmeticException()
}
}
job.join()
//sampleEnd
}
927
The output of this code is:
Exceptions
aggregation
When multiple children of a coroutine fail with an exception, the general rule is "the first exception wins", so the first
exception gets handled. All additional exceptions that happen after the first one are attached to the first exception as
suppressed ones.
import kotlinx.coroutines.*
import java.io.*
@OptIn(DelicateCoroutinesApi::class)
fun main() = runBlocking {
val handler = CoroutineExceptionHandler { _, exception ->
println("CoroutineExceptionHandler got $exception with suppressed
${exception.suppressed.contentToString()}")
}
val job = GlobalScope.launch(handler) {
launch {
try {
delay(Long.MAX_VALUE) // it gets cancelled when another sibling fails with
IOException
} finally {
throw ArithmeticException() // the second exception
}
}
launch {
delay(100)
throw IOException() // the first exception
}
delay(Long.MAX_VALUE)
}
job.join()
}
Note: This above code will work properly only on JDK7+ that supports suppressed exceptions
928
Note that this mechanism currently only works on Java version 1.7+. The JS and Native restrictions are
temporary and will be lifted in the future.
import kotlinx.coroutines.*
import java.io.*
@OptIn(DelicateCoroutinesApi::class)
fun main() = runBlocking {
//sampleStart
val handler = CoroutineExceptionHandler { _, exception ->
println("CoroutineExceptionHandler got $exception")
}
val job = GlobalScope.launch(handler) {
val inner = launch { // all this stack of coroutines will get cancelled
launch {
launch {
throw IOException() // the original exception
}
}
}
try {
inner.join()
} catch (e: CancellationException) {
println("Rethrowing CancellationException with original cause")
throw e // cancellation exception is rethrown, yet the original IOException gets to
the handler
}
}
job.join()
//sampleEnd
}
Supervision
As we have studied before, cancellation is a bidirectional relationship propagating through the whole hierarchy of
coroutines. Let us take a look at the case when unidirectional cancellation is required.
929
A good example of such a requirement is a UI component with the job defined in its scope. If any of the UI's child tasks
have failed, it is not always necessary to cancel (effectively kill) the whole UI component, but if UI component is destroyed
(and its job is cancelled), then it is necessary to fail all child jobs as their results are no longer needed.
Another example is a server process that spawns multiple child jobs and needs to supervise their execution, tracking their
failures and only restarting the failed ones.
Supervision
job
The SupervisorJob can be used for these purposes. It is similar to a regular Job with the only exception that cancellation
is propagated only downwards. This can easily be demonstrated using the following example:
import kotlinx.coroutines.*
930
Supervision
scope
Instead of coroutineScope, we can use supervisorScope for scoped concurrency. It propagates the cancellation in one
direction only and cancels all its children only if it failed itself. It also waits for all children before completion just like
coroutineScope does.
import kotlin.coroutines.*
import kotlinx.coroutines.*
931
import kotlin.coroutines.*
import kotlinx.coroutines.*
Shared
mutable
state
and
concurrency
Coroutines can be executed parallelly using a multi-threaded dispatcher like the Dispatchers.Default. It presents all the
usual parallelism problems. The main problem being synchronization of access to shared mutable state. Some solutions
to this problem in the land of coroutines are similar to the solutions in the multi-threaded world, but others are unique.
The
problem
Let us launch a hundred coroutines all doing the same action thousand times. We'll also measure their completion time
for further comparisons:
932
}
}
}
println("Completed ${n * k} actions in $time ms")
}
We start with a very simple action that increments a shared mutable variable using multi-threaded Dispatchers.Default.
import kotlinx.coroutines.*
import kotlin.system.*
//sampleStart
var counter = 0
What does it print at the end? It is highly unlikely to ever print "Counter = 100000", because a hundred coroutines
increment the counter concurrently from multiple threads without any synchronization.
Volatiles
are
of
no
help
There is a common misconception that making a variable volatile solves concurrency problem. Let us try it:
import kotlinx.coroutines.*
import kotlin.system.*
933
suspend fun massiveRun(action: suspend () -> Unit) {
val n = 100 // number of coroutines to launch
val k = 1000 // times an action is repeated by each coroutine
val time = measureTimeMillis {
coroutineScope { // scope for coroutines
repeat(n) {
launch {
repeat(k) { action() }
}
}
}
}
println("Completed ${n * k} actions in $time ms")
}
//sampleStart
@Volatile // in Kotlin `volatile` is an annotation
var counter = 0
This code works slower, but we still don't get "Counter = 100000" at the end, because volatile variables guarantee
linearizable (this is a technical term for "atomic") reads and writes to the corresponding variable, but do not provide
atomicity of larger actions (increment in our case).
Thread-safe
data
structures
The general solution that works both for threads and for coroutines is to use a thread-safe (aka synchronized, linearizable,
or atomic) data structure that provides all the necessary synchronization for the corresponding operations that needs to
be performed on a shared state. In the case of a simple counter we can use AtomicInteger class which has atomic
incrementAndGet operations:
import kotlinx.coroutines.*
import java.util.concurrent.atomic.*
import kotlin.system.*
934
repeat(n) {
launch {
repeat(k) { action() }
}
}
}
}
println("Completed ${n * k} actions in $time ms")
}
//sampleStart
val counter = AtomicInteger()
This is the fastest solution for this particular problem. It works for plain counters, collections, queues and other standard
data structures and basic operations on them. However, it does not easily scale to complex state or to complex
operations that do not have ready-to-use thread-safe implementations.
Thread
confinement
fine-grained
Thread confinement is an approach to the problem of shared mutable state where all access to the particular shared state
is confined to a single thread. It is typically used in UI applications, where all UI state is confined to the single event-
dispatch/application thread. It is easy to apply with coroutines by using a
single-threaded context.
import kotlinx.coroutines.*
import kotlin.system.*
935
println("Completed ${n * k} actions in $time ms")
}
//sampleStart
val counterContext = newSingleThreadContext("CounterContext")
var counter = 0
This code works very slowly, because it does fine-grained thread-confinement. Each individual increment switches from
multi-threaded Dispatchers.Default context to the single-threaded context using withContext(counterContext) block.
Thread
confinement
coarse-grained
In practice, thread confinement is performed in large chunks, e.g. big pieces of state-updating business logic are
confined to the single thread. The following example does it like that, running each coroutine in the single-threaded
context to start with.
import kotlinx.coroutines.*
import kotlin.system.*
//sampleStart
val counterContext = newSingleThreadContext("CounterContext")
var counter = 0
936
fun main() = runBlocking {
// confine everything to a single-threaded context
withContext(counterContext) {
massiveRun {
counter++
}
}
println("Counter = $counter")
}
//sampleEnd
Mutual
exclusion
Mutual exclusion solution to the problem is to protect all modifications of the shared state with a critical section that is
never executed concurrently. In a blocking world you'd typically use synchronized or ReentrantLock for that. Coroutine's
alternative is called Mutex. It has lock and unlock functions to delimit a critical section. The key difference is that
Mutex.lock() is a suspending function. It does not block a thread.
There is also withLock extension function that conveniently represents mutex.lock(); try { ... } finally { mutex.unlock() }
pattern:
import kotlinx.coroutines.*
import kotlinx.coroutines.sync.*
import kotlin.system.*
//sampleStart
val mutex = Mutex()
var counter = 0
937
// protect each increment with lock
mutex.withLock {
counter++
}
}
}
println("Counter = $counter")
}
//sampleEnd
The locking in this example is fine-grained, so it pays the price. However, it is a good choice for some situations where
you absolutely must modify some shared state periodically, but there is no natural thread that this state is confined to.
Actors
An actor is an entity made up of a combination of a coroutine, the state that is confined and encapsulated into this
coroutine, and a channel to communicate with other coroutines. A simple actor can be written as a function, but an actor
with a complex state is better suited for a class.
There is an actor coroutine builder that conveniently combines actor's mailbox channel into its scope to receive
messages from and combines the send channel into the resulting job object, so that a single reference to the actor can be
carried around as its handle.
The first step of using an actor is to define a class of messages that an actor is going to process. Kotlin's sealed classes
are well suited for that purpose. We define CounterMsg sealed class with IncCounter message to increment a counter and
GetCounter message to get its value. The later needs to send a response. A CompletableDeferred communication
primitive, that represents a single value that will be known (communicated) in the future, is used here for that purpose.
Then we define a function that launches an actor using an actor coroutine builder:
938
The main code is straightforward:
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*
import kotlin.system.*
//sampleStart
fun main() = runBlocking<Unit> {
val counter = counterActor() // create the actor
withContext(Dispatchers.Default) {
massiveRun {
counter.send(IncCounter)
}
}
// send a message to get a counter value from an actor
val response = CompletableDeferred<Int>()
counter.send(GetCounter(response))
println("Counter = ${response.await()}")
counter.close() // shutdown the actor
}
//sampleEnd
It does not matter (for correctness) what context the actor itself is executed in. An actor is a coroutine and a coroutine is
939
executed sequentially, so confinement of the state to the specific coroutine works as a solution to the problem of shared
mutable state. Indeed, actors may modify their own private state, but can only affect each other through messages
(avoiding the need for any locks).
Actor is more efficient than locking under load, because in this case it always has work to do and it does not have to
switch to a different context at all.
Note that an actor coroutine builder is a dual of produce coroutine builder. An actor is associated with the
channel that it receives messages from, while a producer is associated with the channel that it sends elements
to.
Select
expression
(experimental)
Select expression makes it possible to await multiple suspending functions simultaneously and select the first one that
becomes available.
Select expressions are an experimental feature of kotlinx.coroutines. Their API is expected to evolve in the
upcoming updates of the kotlinx.coroutines library with potentially breaking changes.
Selecting
from
channels
Let us have two producers of strings: fizz and buzz. The fizz produces "Fizz" string every 300 ms:
Using receive suspending function we can receive either from one channel or the other. But select expression allows us to
receive from both simultaneously using its onReceive clauses:
940
suspend fun selectFizzBuzz(fizz: ReceiveChannel<String>, buzz: ReceiveChannel<String>) {
select<Unit> { // <Unit> means that this select expression does not produce any result
fizz.onReceive { value -> // this is the first select clause
println("fizz -> '$value'")
}
buzz.onReceive { value -> // this is the second select clause
println("buzz -> '$value'")
}
}
}
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*
import kotlinx.coroutines.selects.*
941
The result of this code is:
Selecting
on
close
The onReceive clause in select fails when the channel is closed causing the corresponding select to throw an exception.
We can use onReceiveCatching clause to perform a specific action when the channel is closed. The following example
also shows that select is an expression that returns the result of its selected clause:
Let's use it with channel a that produces "Hello" string four times and channel b that produces "World" four times:
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*
import kotlinx.coroutines.selects.*
942
val value = it.getOrNull()
if (value != null) {
"b -> '$value'"
} else {
"Channel 'b' is closed"
}
}
}
fun main() = runBlocking<Unit> {
//sampleStart
val a = produce<String> {
repeat(4) { send("Hello $it") }
}
val b = produce<String> {
repeat(4) { send("World $it") }
}
repeat(8) { // print first eight results
println(selectAorB(a, b))
}
coroutineContext.cancelChildren()
//sampleEnd
}
The result of this code is quite interesting, so we'll analyze it in more detail:
First of all, select is biased to the first clause. When several clauses are selectable at the same time, the first one among
them gets selected. Here, both channels are constantly producing strings, so a channel, being the first clause in select,
wins. However, because we are using unbuffered channel, the a gets suspended from time to time on its send invocation
and gives a chance for b to send, too.
The second observation, is that onReceiveCatching gets immediately selected when the channel is already closed.
Selecting
to
send
Select expression has onSend clause that can be used for a great good in combination with a biased nature of selection.
Let us write an example of producer of integers that sends its values to a side channel when the consumers on its primary
943
channel cannot keep up with it:
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*
import kotlinx.coroutines.selects.*
Consuming 1
Side channel has 2
Side channel has 3
Consuming 4
Side channel has 5
Side channel has 6
944
Consuming 7
Side channel has 8
Side channel has 9
Consuming 10
Done consuming
Selecting
deferred
values
Deferred values can be selected using onAwait clause. Let us start with an async function that returns a deferred string
value after a random delay:
Now the main function awaits for the first of them to complete and counts the number of deferred values that are still
active. Note that we've used here the fact that select expression is a Kotlin DSL, so we can provide clauses for it using an
arbitrary code. In this case we iterate over a list of deferred values to provide onAwait clause for each deferred value.
import kotlinx.coroutines.*
import kotlinx.coroutines.selects.*
import java.util.*
fun CoroutineScope.asyncString(time: Int) = async {
delay(time.toLong())
"Waited for $time ms"
}
945
val countActive = list.count { it.isActive }
println("$countActive coroutines are still active")
//sampleEnd
}
Switch
over
a
channel
of
deferred
values
Let us write a channel producer function that consumes a channel of deferred string values, waits for each received
deferred value, but only until the next deferred value comes over or the channel is closed. This example puts together
onReceiveCatching and onAwait clauses in the same select:
To test it, we'll use a simple async function that resolves to a specified string after a specified time:
946
The main function just launches a coroutine to print results of switchMapDeferreds and sends some test data to it:
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*
import kotlinx.coroutines.selects.*
fun CoroutineScope.switchMapDeferreds(input: ReceiveChannel<Deferred<String>>) = produce<String>
{
var current = input.receive() // start with first received deferred value
while (isActive) { // loop while not cancelled/closed
val next = select<Deferred<String>?> { // return next deferred value from this select or
null
input.onReceiveCatching { update ->
update.getOrNull()
}
current.onAwait { value ->
send(value) // send value that current deferred has produced
input.receiveCatching().getOrNull() // and use the next deferred from the input
channel
}
}
if (next == null) {
println("Channel was closed")
break // out of loop
} else {
current = next
}
}
}
947
The result of this code:
BEGIN
Replace
END
Channel was closed
Debug
coroutines
using
IntelliJ
IDEA
–
tutorial
This tutorial demonstrates how to create Kotlin coroutines and debug them using IntelliJ IDEA.
The tutorial assumes you have prior knowledge of the coroutines concept.
Create
coroutines
1. Open a Kotlin project in IntelliJ IDEA. If you don't have a project, create one.
The src directory contains Kotlin source files and resources. The main.kt file contains sample code that will print Hello
World!.
Use the async() function to create coroutines that compute deferred values a and b.
Use the println() function to print computing status and the result of multiplication to the output.
import kotlinx.coroutines.*
948
4. Build the code by clicking Build Project.
Build an application
Debug
coroutines
1. Set breakpoints at the lines with the println() function call:
2. Run the code in debug mode by clicking Debug next to the run configuration at the top of the screen.
949
Build a console application
The Coroutines tab contains information on running or suspended coroutines. It shows that there are three
coroutines. The first one has the RUNNING status, and the other two have the CREATED status.
3. Resume the debugger session by clicking Resume program in the Debug tool window:
950
The first coroutine has the SUSPENDED status – it is waiting for the values so it can multiply them.
The second coroutine is calculating the a value – it has the RUNNING status.
The third coroutine has the CREATED status and isn’t calculating the value of b.
4. Resume the debugger session by clicking Resume program in the Debug tool window:
The first coroutine has the SUSPENDED status – it is waiting for the values so it can multiply them.
The third coroutine is calculating the value of b – it has the RUNNING status.
Using IntelliJ IDEA debugger, you can dig deeper into each coroutine to debug your code.
Debug
Kotlin
Flow
using
IntelliJ
IDEA
–
tutorial
This tutorial demonstrates how to create Kotlin Flow and debug it using IntelliJ IDEA.
The tutorial assumes you have prior knowledge of the coroutines and Kotlin Flow concepts.
Create
a
Kotlin
flow
Create a Kotlin flow with a slow emitter and a slow collector:
1. Open a Kotlin project in IntelliJ IDEA. If you don't have a project, create one.
951
2. Open the main.kt file in src/main/kotlin.
The src directory contains Kotlin source files and resources. The main.kt file contains sample code that will print Hello
World!.
Use the delay() function to imitate CPU-consuming blocking code. It suspends the coroutine for 100 ms without
blocking the thread.
Produce the values in the for loop using the emit() function.
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
import kotlin.system.*
Use the delay() function to imitate CPU-consuming code. It suspends the coroutine for 300 ms without blocking the
thread.
Print the collected value from the flow using the println() function.
952
Build an application
Debug
the
coroutine
1. Set a breakpoint at the at the line where the emit() function is called:
2. Run the code in debug mode by clicking Debug next to the run configuration at the top of the screen.
953
Build a console application
The Variables tab contains variables in the current context. It tells us that the flow is emitting the first value.
3. Resume the debugger session by clicking Resume program in the Debug tool window. The program stops at the same
breakpoint.
954
Debug the coroutine
Add
a
concurrently
running
coroutine
1. Open the main.kt file in src/main/kotlin.
Add a call to the buffer() function to run the emitter and collector concurrently. buffer() stores emitted values and
runs the flow collector in a separate coroutine.
Debug
a
Kotlin
flow
with
two
coroutines
1. Set a new breakpoint at println(value).
2. Run the code in debug mode by clicking Debug next to the run configuration at the top of the screen.
955
Build a console application
In the Coroutines tab, you can see that there are two coroutines running concurrently. The flow collector and emitter
run in separate coroutines because of the buffer() function. The buffer() function buffers emitted values from the flow.
The emitter coroutine has the RUNNING status, and the collector coroutine has the SUSPENDED status.
3. Resume the debugger session by clicking Resume program in the Debug tool window.
Debugging coroutines
Now the collector coroutine has the RUNNING status, while the emitter coroutine has the SUSPENDED status.
You can dig deeper into each coroutine to debug your code.
Serialization
Serialization is the process of converting data used by an application to a format that can be transferred over a network or
stored in a database or a file. In turn, deserialization is the opposite process of reading data from an external source and
converting it into a runtime object. Together they are an essential part of most applications that exchange data with third
parties.
Some data serialization formats, such as JSON and protocol buffers are particularly common. Being language-neutral and
platform-neutral, they enable data exchange between systems written in any modern language.
956
In Kotlin, data serialization tools are available in a separate component, kotlinx.serialization. It consists of two main parts:
the Gradle plugin – org.jetbrains.kotlin.plugin.serialization and the runtime libraries.
Libraries
kotlinx.serialization provides sets of libraries for all supported platforms – JVM, JavaScript, Native – and for various
serialization formats – JSON, CBOR, protocol buffers, and others. You can find the complete list of supported
serialization formats below.
All Kotlin serialization libraries belong to the org.jetbrains.kotlinx: group. Their names start with kotlinx-serialization- and
have suffixes that reflect the serialization format. Examples:
Platform-specific artifacts are handled automatically; you don't need to add them manually. Use the same dependencies
in JVM, JS, Native, and multiplatform projects.
Note that the kotlinx.serialization libraries use their own versioning structure, which doesn't match Kotlin's versioning.
Check out the releases on GitHub to find the latest versions.
Formats
kotlinx.serialization includes libraries for various serialization formats:
JSON: kotlinx-serialization-json
CBOR: kotlinx-serialization-cbor
Properties: kotlinx-serialization-properties
Note that all libraries except JSON serialization ( kotlinx-serialization-core) are Experimental, which means their API can be
changed without notice.
There are also community-maintained libraries that support more serialization formats, such as YAML or Apache Avro. For
detailed information about available serialization formats, see the kotlinx.serialization documentation.
Example:
JSON
serialization
Let’s take a look at how to serialize Kotlin objects into JSON.
Before starting, you’ll need to configure your build script so that you can use Kotlin serialization tools in your project:
957
1. Apply the Kotlin serialization Gradle plugin org.jetbrains.kotlin.plugin.serialization (or kotlin(“plugin.serializationâ€)
in the Kotlin Gradle DSL).
Kotlin
plugins {
kotlin("jvm") version "1.5.31"
kotlin("plugin.serialization") version "1.5.31"
}
Groovy
plugins {
id 'org.jetbrains.kotlin.jvm' version '1.5.31'
id 'org.jetbrains.kotlin.plugin.serialization' version '1.5.31'
}
Kotlin
dependencies {
implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.3.0")
}
Groovy
dependencies {
implementation 'org.jetbrains.kotlinx:kotlinx-serialization-json:1.3.0'
}
Now you're ready to use the serialization API in your code. The API is located in the the kotlinx.serialization package and
its format-specific subpackages such as kotlinx.serialization.json.
import kotlinx.serialization.Serializable
@Serializable
data class Data(val a: Int, val b: String)
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
958
import kotlinx.serialization.encodeToString
@Serializable
data class Data(val a: Int, val b: String)
fun main() {
val json = Json.encodeToString(Data(42, "str"))
}
As a result, you get a string containing the state of this object in the JSON format: {"a": 42, "b": "str"}
You can also serialize object collections, such as lists, in a single call.
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
import kotlinx.serialization.decodeFromString
@Serializable
data class Data(val a: Int, val b: String)
fun main() {
val obj = Json.decodeFromString<Data>("""{"a":42, "b": "str"}""")
}
For more information about serialization in Kotlin, see the Kotlin Serialization Guide.
Keywords
and
operators
Hard
keywords
The following tokens are always interpreted as keywords and cannot be used as identifiers:
as
is used for type casts
959
do begins a do/while loop (loop with postcondition)
else defines the branch of an if expression which is executed when the condition is false
if begins an if expression
in
specifies the object being iterated in a for loop
is used as an infix operator to check that a value belongs to a range, a collection or another entity that defines the
'contains' method
!in
is used as an operator to check that a value does NOT belong to a range, a collection or another entity that defines
the 'contains' method
is
checks that a value has a certain type
!is
checks that a value does NOT have a certain type
null is a constant representing an object reference that doesn't point to any object
super
refers to the superclass implementation of a method or property
960
this
refers to the current receiver
Soft
keywords
The following tokens act as keywords in the context when they are applicable and can be used as identifiers in other
contexts:
by
delegates the implementation of an interface to another object
finally begins a block that is always executed when a try block exits
get
declares the getter of a property
961
import imports a declaration from another package into the current file
set
declares the setter of a property
Modifier
keywords
The following tokens act as keywords in modifier lists of declarations and can be used as identifiers in other contexts:
external marks a declaration as implemented not in Kotlin (accessible through JNI or in JavaScript)
inline tells the compiler to inline the function and the lambdas passed to it at the call site
inner allows referring to the outer class instance from a nested class
962
internal marks a declaration as visible in the current module
protected marks a declaration as visible in the current class and its subclasses
tailrec marks a function as tail-recursive (allowing the compiler to replace recursion with iteration)
Special
identifiers
The following identifiers are defined by the compiler in specific contexts and can be used as regular identifiers in other
contexts:
field is used inside a property accessor to refer to the backing field of the property
Operators
and
special
symbols
Kotlin supports the following operators and special symbols:
+, -, *, /, %- mathematical operators
* is also used to pass an array to a vararg parameter
=
assignment operator
963
+=, -=, *=, /=, %=- augmented assignment operators
&&, ||, !- logical 'and', 'or', 'not' operators (for bitwise operations, use corresponding infix functions)
==, !=- equality operators (translated to calls of equals() for non-primitive types)
<, >, <=, >=- comparison operators (translated to calls of compareTo() for non-primitive types)
?. performs a safe call (calls a method or accesses a property if the receiver is non-null)
?: takes the right-hand value if the left-hand value is null (the elvis operator)
.. creates a range
->
separates the parameters and body of a lambda expression
@
introduces an annotation
_
substitutes an unused parameter in a lambda expression
964
Gradle
In order to build a Kotlin project with Gradle, you should apply the Kotlin Gradle plugin to your project and configure the
dependencies.
Plugin
and
versions
Apply the Kotlin Gradle plugin by using the Gradle plugins DSL.
The Kotlin Gradle plugin and the kotlin-multiplatform plugin 1.5.31 require Gradle 6.1 or later.
Kotlin
plugins {
kotlin("<...>") version "1.5.31"
}
Groovy
plugins {
id 'org.jetbrains.kotlin.<...>' version '1.5.31'
}
The placeholder <...> should be replaced with the name of one of the plugins that will be discussed in subsequent
sections.
Targeting
multiple
platforms
Projects targeting multiple platforms, called multiplatform projects, require the kotlin-multiplatform plugin. Learn more
about the plugin.
Kotlin
plugins {
kotlin("multiplatform") version "1.5.31"
}
Groovy
965
plugins {
id 'org.jetbrains.kotlin.multiplatform' version '1.5.31'
}
Targeting
the
JVM
To target the JVM, apply the Kotlin JVM plugin.
Kotlin
plugins {
kotlin("jvm") version "1.5.31"
}
Groovy
plugins {
id "org.jetbrains.kotlin.jvm" version "1.5.31"
}
The version should be literal in this block, and it cannot be applied from another build script.
Applying Kotlin plugins with apply in the Kotlin Gradle DSL is not recommended – see why.
Kotlin
and
Java
sources
Kotlin sources and Java sources can be stored in the same folder, or they can be placed in different folders. The default
convention is to use different folders:
project
- src
- main (root)
- kotlin
- java
The corresponding sourceSets property should be updated if you are not using the default convention:
Kotlin
966
sourceSets.main {
java.srcDirs("src/main/myJava", "src/main/myKotlin")
}
Groovy
sourceSets {
main.kotlin.srcDirs += 'src/main/myKotlin'
main.java.srcDirs += 'src/main/myJava'
}
Targeting
JavaScript
When targeting only JavaScript, use the kotlin-js plugin. Learn more
Kotlin
plugins {
kotlin("js") version "1.5.31"
}
Groovy
plugins {
id 'org.jetbrains.kotlin.js' version '1.5.31'
}
Kotlin
and
Java
sources
for
JavaScript
This plugin only works for Kotlin files, so it is recommended that you keep Kotlin and Java files separate (if the project
contains Java files). If you don't store them separately, specify the source folder in the sourceSets block:
Kotlin
kotlin {
sourceSets["main"].apply {
kotlin.srcDir("src/main/myKotlin")
}
}
Groovy
kotlin {
sourceSets {
967
main.kotlin.srcDirs += 'src/main/myKotlin'
}
}
Targeting
Android
It's recommended to use Android Studio for creating Android applications. Learn how to use Android Gradle plugin.
Configuring
dependencies
To add a dependency on a library, set the dependency of the required type (for example, implementation) in the
dependencies block of the source sets DSL.
Kotlin
kotlin {
sourceSets {
val commonMain by getting {
dependencies {
implementation("com.example:my-library:1.0")
}
}
}
}
Groovy
kotlin {
sourceSets {
commonMain {
dependencies {
implementation 'com.example:my-library:1.0'
}
}
}
}
Dependency
types
Choose the dependency type based on your requirements.
968
Type Description When to use
api Used both during compilation and at runtime and is exported If any type from a dependency is used in the
to library consumers. public API of the current module, use an api
dependency.
implementation Used during compilation and at runtime for the current Use for dependencies needed for the
module, but is not exposed for compilation of other modules internal logic of a module.
depending on the one with the `implementation` dependency.
compileOnly Used for compilation of the current module and is not Use for APIs which have a third-party
available at runtime nor during compilation of other modules. implementation available at runtime.
Dependency
on
the
standard
library
A dependency on the standard library (stdlib) is added automatically to each source set. The version of the standard
library used is the same as the version of the Kotlin Gradle plugin.
For platform-specific source sets, the corresponding platform-specific variant of the library is used, while a common
standard library is added to the rest. The Kotlin Gradle plugin will select the appropriate JVM standard library depending
on the kotlinOptions.jvmTarget compiler option of your Gradle build script.
If you declare a standard library dependency explicitly (for example, if you need a different version), the Kotlin Gradle
plugin won't override it or add a second standard library.
If you do not need a standard library at all, you can add the opt-out option to the gradle.properties:
kotlin.stdlib.default.dependency=false
Set
dependencies
on
test
libraries
The kotlin.test API is available for testing Kotlin projects on all supported platforms. Add the dependency kotlin-test to the
commonTest source set, and the Gradle plugin will infer the corresponding test dependencies for each test source set:
969
Kotlin/Native targets do not require additional test dependencies, and the kotlin.test API implementations are built-in.
Kotlin
kotlin {
sourceSets {
val commonTest by getting {
dependencies {
implementation(kotlin("test")) // This brings all the platform dependencies
automatically
}
}
}
}
Groovy
kotlin {
sourceSets {
commonTest {
dependencies {
implementation kotlin("test") // This brings all the platform dependencies
automatically
}
}
}
}
You can use shorthand for a dependency on a Kotlin module, for example, kotlin("test") for
"org.jetbrains.kotlin:kotlin-test".
You can use the kotlin-test dependency in any shared or platform-specific source set as well.
For Kotlin/JVM, Gradle uses JUnit 4 by default. Therefore, the kotlin("test") dependency resolves to the variant for JUnit 4,
namely kotlin-test-junit.
You can choose JUnit 5 or TestNG by calling useJUnitPlatform() or useTestNG() in the test task of your build script. The
following example is for an MPP project:
Kotlin
kotlin {
jvm {
testRuns["test"].executionTask.configure {
useJUnitPlatform()
}
}
sourceSets {
val commonTest by getting {
970
dependencies {
implementation(kotlin("test"))
}
}
}
}
Groovy
kotlin {
jvm {
testRuns["test"].executionTask.configure {
useJUnitPlatform()
}
}
sourceSets {
commonTest {
dependencies {
implementation kotlin("test")
}
}
}
}
Kotlin
dependencies {
testImplementation(kotlin("test"))
}
tasks {
test {
useTestNG()
}
}
Groovy
dependencies {
testImplementation 'org.jetbrains.kotlin:kotlin-test'
}
test {
useTestNG()
}
If you need to use a different JVM test framework, disable automatic testing framework selection by adding the line
971
kotlin.test.infer.jvm.variant=false to the project's gradle.properties file. After doing this, add the framework as a Gradle
dependency.
If you had used a variant of kotlin("test") in your build script explicitly and project build stopped working with a
compatibility conflict, see this issue in the Compatibility Guide.
Set
a
dependency
on
a
kotlinx
library
If you use a kotlinx library and need a platform-specific dependency, you can use platform-specific variants of libraries
with suffixes such as -jvm or -js, for example, kotlinx-coroutines-core-jvm. You can also use the library's base artifact
name instead – kotlinx-coroutines-core.
Kotlin
kotlin {
sourceSets {
val jvmMain by getting {
dependencies {
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core-jvm:1.5.2")
}
}
}
}
Groovy
kotlin {
sourceSets {
jvmMain {
dependencies {
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core-jvm:1.5.2'
}
}
}
}
If you use a multiplatform library and need to depend on the shared code, set the dependency only once, in the shared
source set. Use the library's base artifact name, such as kotlinx-coroutines-core or ktor-client-core.
Kotlin
kotlin {
sourceSets {
val commonMain by getting {
dependencies {
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.5.2")
}
}
}
}
972
Groovy
kotlin {
sourceSets {
commonMain {
dependencies {
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.5.2'
}
}
}
}
Set
dependencies
at
the
top
level
Alternatively, you can specify the dependencies at the top level, using the following pattern for the configuration names:
<sourceSetName><DependencyType>. This can be helpful for some Gradle built-in dependencies, like gradleApi(),
localGroovy(), or gradleTestKit(), which are not available in the source sets' dependency DSL.
Kotlin
dependencies {
"commonMainImplementation"("com.example:my-library:1.0")
}
Groovy
dependencies {
commonMainImplementation 'com.example:my-library:1.0'
}
Annotation
processing
Kotlin supports annotation processing via the Kotlin annotation processing tool kapt.
Incremental
compilation
The Kotlin Gradle plugin supports incremental compilation. Incremental compilation tracks changes to source files
between builds so only files affected by these changes are compiled.
Incremental compilation is supported for Kotlin/JVM and Kotlin/JS projects and is enabled by default.
973
kotlin.incremental.js=false for Kotlin/JS projects.
The parameter should be added to each subsequent build, and any build with incremental compilation disabled
invalidates incremental caches.
Gradle
build
cache
support
The Kotlin plugin uses the Gradle build cache, which stores the build outputs for reuse in future builds.
To disable caching for all Kotlin tasks, set the system property flag kotlin.caching.enabled to false (run the build with the
argument -Dkotlin.caching.enabled=false).
If you use kapt, note that kapt annotation processing tasks are not cached by default. However, you can enable caching
for them manually.
Gradle
configuration
cache
support
The configuration cache is available in Gradle 6.5 and later as an experimental feature. You can check the
Gradle releases page to see whether it has been promoted to stable.
The Kotlin plugin uses the Gradle configuration cache, which speeds up the build process by reusing the results of the
configuration phase.
See the Gradle documentation to learn how to enable the configuration cache. After you enable this feature, the Kotlin
Gradle plugin will automatically start using it.
Compiler
options
Use the kotlinOptions property of a Kotlin compilation task to specify additional compilation options.
When targeting the JVM, the tasks are called compileKotlin for production code and compileTestKotlin for test code. The
tasks for custom source sets are named according to their compile<Name>Kotlin patterns.
The names of the tasks in Android Projects contain build variant names and follow the compile<BuildVariant>Kotlin
pattern, for example, compileDebugKotlin or compileReleaseUnitTestKotlin.
When targeting JavaScript, the tasks are called compileKotlinJs for production code and compileTestKotlinJs for test
code, and compile<Name>KotlinJs for custom source sets.
974
Kotlin
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
// ...
compileKotlin.kotlinOptions.suppressWarnings = true
Groovy
compileKotlin {
kotlinOptions.suppressWarnings = true
}
//or
compileKotlin {
kotlinOptions {
suppressWarnings = true
}
}
Note that with the Gradle Kotlin DSL, you should get the task from the project's tasks first.
Use the Kotlin2JsCompile and KotlinCompileCommon types for JS and common targets, respectively.
It is also possible to configure all of the Kotlin compilation tasks in the project:
Kotlin
tasks.withType<org.jetbrains.kotlin.gradle.tasks.KotlinCompile>().configureEach {
kotlinOptions { /*...*/ }
}
Groovy
tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).configureEach {
kotlinOptions { /*...*/ }
}
Attributes
common
to
JVM,
JS,
and
JS
DCE
975
Name Description Possible values Default value
Attributes
common
to
JVM
and
JS
apiVersion Restrict the use of declarations to those from the specified "1.3" (DEPRECATED), "1.4", "1.5",
version of bundled libraries "1.6" (EXPERIMENTAL)
languageVersion Provide source compatibility with the specified version of "1.3" (DEPRECATED), "1.4", "1.5",
Kotlin "1.6" (EXPERIMENTAL)
Attributes
specific
to
JS
976
Name Description Possible Default value
values
Attributes
specific
to
JVM
javaParameters Generate metadata for Java 1.8 reflection on method parameters false
jdkHome Include a custom JDK from the specified location into the classpath
instead of the default JAVA_HOME. Direct setting is deprecated sinÑe
1.5.30, use other ways to set this option.
977
Name Description Possible values Default
value
jvmTarget Target version of the generated JVM bytecode "1.6" (DEPRECATED), "1.8"
"1.8", "9", "10", "11", "12",
"13", "14", "15", "16"
noJdk Don't automatically include the Java runtime into the classpath false
main and test source set compile tasks are not related.
For such related tasks, the Kotlin Gradle plugin checks for JVM target compatibility. Different values of jvmTarget in the
kotlin extension and targetCompatibility in the java extension cause incompatibility. For example: the compileKotlin task
has jvmTarget=1.8, and the compileJava task has (or inherits) targetCompatibility=15.
Control the behavior of this check by setting the kotlin.jvm.target.validation.mode property in the build.gradle file equal to:
warning – the default value; the Kotlin Gradle plugin will print a warning message.
ignore – the plugin will skip the check and won't produce any messages.
For Gradle from 6.1 to 6.6 with the UsesKotlinJavaToolchain interface and the Task DSL.
For Gradle 6.7 and later with Java toolchains or the Task DSL to set a local JDK.
When you use a custom JDK, note that kapt task workers use process isolation mode only, and ignore the
978
kapt.workers.isolation property.
As before, if you don't set the toolchain or the jdkHome option, the Kotlin/JVM compilation uses the current user's JDK.
Use a JDK and a JRE that are different from the Gradle ones to run compilations, tests, and executables.
With toolchains support, Gradle can autodetect local JDKs and install missing JDKs that Gradle requires for the build.
Now Gradle itself can run on any JDK and still reuse the remote build cache feature for tasks that depend on a major JDK
version.
The Kotlin Gradle plugin supports Java toolchains for Kotlin/JVM compilation tasks. JS and Native tasks don't use
toolchains. The Kotlin compiler always uses the JDK the Gradle daemon is running on. A Java toolchain:
Sets the kotlinOptions.jvmTarget to the toolchain's JDK version if the user doesn't set the jvmTarget option explicitly. If
the user doesn't configure the toolchain, the jvmTarget field will use the default value. Learn more about JVM target
compatibility.
Use the following code to set a toolchain. Replace the placeholder <MAJOR_JDK_VERSION> with the JDK version you
would like to use:
Kotlin
kotlin {
jvmToolchain {
(this as
JavaToolchainSpec).languageVersion.set(JavaLanguageVersion.of(<MAJOR_JDK_VERSION>)) // "8"
}
}
Groovy
kotlin {
jvmToolchain {
languageVersion.set(JavaLanguageVersion.of(<MAJOR_JDK_VERSION>)) // "8"
}
}
979
Note that setting a toolchain via the kotlin extension will update the toolchain for Java compile tasks as well.
You can set a toolchain via the java extension, and Kotlin compilation tasks will use it:
java {
toolchain {
languageVersion.set(JavaLanguageVersion.of(<MAJOR_JDK_VERSION>)) // "8"
}
}
To set any JDK (even local) for the specific task, use the Task DSL.
Kotlin
Groovy
Or you can specify the path to your local JDK and replace the placeholder <LOCAL_JDK_VERSION> with this JDK
version:
project.tasks
.matching { it is UsesKotlinJavaToolchain && it.name == "compileKotlin" }
.configureEach {
it.kotlinJavaToolchain.jdk.use(
"/path/to/local/jdk", // Put a path to your JDK
980
JavaVersion.<LOCAL_JDK_VERSION> // For example, JavaVersion.17
)
}
Generating
documentation
To generate documentation for Kotlin projects, use Dokka; please refer to the Dokka README for configuration
instructions. Dokka supports mixed-language projects and can generate output in multiple formats, including standard
JavaDoc.
OSGi
For OSGi support see the Kotlin OSGi page.
Using
the
Gradle
Kotlin
DSL
When using Gradle Kotlin DSL, apply Kotlin plugins using the plugins { ... } block. If you apply them with apply { plugin(...) }
instead, you may encounter unresolved references to the extensions generated by Gradle Kotlin DSL. To resolve that, you
can comment out the erroneous usages, run the Gradle task kotlinDslAccessorsSnapshot, then uncomment the usages
back and rerun the build or reimport the project into the IDE.
Kotlin
daemon
and
using
it
with
Gradle
The Kotlin daemon:
Runs separately when you compile the project with an IntelliJ IDEA built-in build system.
The Kotlin daemon starts at the Gradle execution stage when one of Kotlin compile tasks starts compiling the sources.
The Kotlin daemon stops along with the Gradle daemon or after two idle hours with no Kotlin compilation.
The Kotlin daemon uses the same JDK that the Gradle daemon does.
Setting
Kotlin
daemon's
JVM
arguments
Each of the options in the following list overrides the ones that came before it:
If nothing is specified, the Kotlin daemon inherits arguments from the Gradle daemon. For example, in the
gradle.properties file:
org.gradle.jvmargs=-Xmx1500m -Xms=500m
981
If the Gradle daemon's JVM arguments have the kotlin.daemon.jvm.options system property – use it in the
gradle.properties file:
org.gradle.jvmargs=-Dkotlin.daemon.jvm.options=-Xmx1500m -Xms=500m
kotlin.daemon.jvmargs=-Xmx1500m -Xms=500m
Kotlin
kotlin {
kotlinDaemonJvmArgs = listOf("-Xmx486m", "-Xms256m", "-XX:+UseParallelGC")
}
Groovy
kotlin {
kotlinDaemonJvmArgs = ["-Xmx486m", "-Xms256m", "-XX:+UseParallelGC"]
}
Kotlin
tasks
.matching { it.name == "compileKotlin" && it is CompileUsingKotlinDaemon }
.configureEach {
(this as CompileUsingKotlinDaemon).kotlinDaemonJvmArguments.set(listOf("-Xmx486m", "-
Xms256m", "-XX:+UseParallelGC"))
}
Groovy
tasks
.matching { it.name == "compileKotlin" && it instanceof CompileUsingKotlinDaemon }
.configureEach {
kotlinDaemonJvmArguments.set(["-Xmx1g", "-Xms512m"])
}
982
In this case a new Kotlin daemon instance can start on task execution. Learn more about Kotlin daemon's
behavior with JVM arguments.
It is expected to have multiple instances of the Kotlin daemon running at the same time when different subprojects or
tasks have different sets of JVM arguments.
A new Kotlin daemon instance starts only when Gradle runs a related compilation task and existing Kotlin daemons do
not have the same set of JVM arguments. Imagine that your project has a lot of subprojects. Most of them require
some heap memory for a Kotlin daemon, but one module requires a lot (though it is rarely compiled). In this case, you
should provide a different set of JVM arguments for such a module, so a Kotlin daemon with a larger heap size would
start only for developers who touch this specific module.
If you are already running a Kotlin daemon that has enough heap size to handle the compilation request,
even if other requested JVM arguments are different, this daemon will be reused instead of starting a new
one.
If the Xmx is not specified, the Kotlin daemon will inherit it from the Gradle daemon.
Maven
Plugin
and
versions
The kotlin-maven-plugin compiles Kotlin sources and modules. Currently, only Maven v3 is supported.
Define the version of Kotlin you want to use via a kotlin.version property:
<properties>
<kotlin.version>1.5.31</kotlin.version>
</properties>
Dependencies
Kotlin has an extensive standard library that can be used in your applications. To use the standard library in your project,
add the following dependency in the pom file:
<dependencies>
983
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib</artifactId>
<version>${kotlin.version}</version>
</dependency>
</dependencies>
If you're targeting JDK 7 or JDK 8, you can use extended versions of the Kotlin standard library. They contain additional
extension functions for APIs added in new JDK versions. Instead of kotlin-stdlib, use kotlin-stdlib-jdk7 or kotlin-stdlib-
jdk8, depending on your JDK version.
For Kotlin versions older that 1.2, use kotlin-stdlib-jre7 and kotlin-stdlib-jre8.
If your project uses Kotlin reflection or testing facilities, you need to add the corresponding dependencies as well. The
artifact IDs are kotlin-reflect for the reflection library, and kotlin-test and kotlin-test-junit for the testing libraries.
Compile
Kotlin-only
source
code
To compile source code, specify the source directories in the <build> tag:
<build>
<sourceDirectory>${project.basedir}/src/main/kotlin</sourceDirectory>
<testSourceDirectory>${project.basedir}/src/test/kotlin</testSourceDirectory>
</build>
<build>
<plugins>
<plugin>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-plugin</artifactId>
<version>${kotlin.version}</version>
<executions>
<execution>
<id>compile</id>
<goals>
<goal>compile</goal>
</goals>
</execution>
<execution>
<id>test-compile</id>
<goals>
<goal>test-compile</goal>
</goals>
</execution>
</executions>
</plugin>
984
</plugins>
</build>
Compile
Kotlin
and
Java
sources
To compile projects that include Kotlin and Java source code, invoke the Kotlin compiler before the Java compiler. In
maven terms that means that kotlin-maven-plugin should be run before maven-compiler-plugin using the following
method, making sure that the kotlin plugin comes before the maven-compiler-plugin in your pom.xml file:
<build>
<plugins>
<plugin>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-plugin</artifactId>
<version>${kotlin.version}</version>
<executions>
<execution>
<id>compile</id>
<goals>
<goal>compile</goal>
</goals>
<configuration>
<sourceDirs>
<sourceDir>${project.basedir}/src/main/kotlin</sourceDir>
<sourceDir>${project.basedir}/src/main/java</sourceDir>
</sourceDirs>
</configuration>
</execution>
<execution>
<id>test-compile</id>
<goals> <goal>test-compile</goal> </goals>
<configuration>
<sourceDirs>
<sourceDir>${project.basedir}/src/test/kotlin</sourceDir>
<sourceDir>${project.basedir}/src/test/java</sourceDir>
</sourceDirs>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<executions>
<!-- Replacing default-compile as it is treated specially by maven -->
<execution>
<id>default-compile</id>
<phase>none</phase>
</execution>
<!-- Replacing default-testCompile as it is treated specially by maven -->
<execution>
<id>default-testCompile</id>
<phase>none</phase>
</execution>
<execution>
985
<id>java-compile</id>
<phase>compile</phase>
<goals>
<goal>compile</goal>
</goals>
</execution>
<execution>
<id>java-test-compile</id>
<phase>test-compile</phase>
<goals>
<goal>testCompile</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
Incremental
compilation
To make your builds faster, you can enable incremental compilation for Maven by defining the kotlin.compiler.incremental
property:
<properties>
<kotlin.compiler.incremental>true</kotlin.compiler.incremental>
</properties>
Annotation
processing
See the description of Kotlin annotation processing tool (kapt).
Jar
file
To create a small Jar file containing just the code from your module, include the following under build->plugins in your
Maven pom.xml file, where main.class is defined as a property and points to the main Kotlin or Java class:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.6</version>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<mainClass>${main.class}</mainClass>
</manifest>
</archive>
986
</configuration>
</plugin>
Self-contained
Jar
file
To create a self-contained Jar file containing the code from your module along with dependencies, include the following
under build->plugins in your Maven pom.xml file, where main.class is defined as a property and points to the main Kotlin
or Java class:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.6</version>
<executions>
<execution>
<id>make-assembly</id>
<phase>package</phase>
<goals> <goal>single</goal> </goals>
<configuration>
<archive>
<manifest>
<mainClass>${main.class}</mainClass>
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
</execution>
</executions>
</plugin>
This self-contained jar file can be passed directly to a JRE to run your application:
Specifying
compiler
options
Additional options and arguments for the compiler can be specified as tags under the <configuration> element of the
Maven plugin node:
<plugin>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-plugin</artifactId>
<version>${kotlin.version}</version>
<executions>...</executions>
<configuration>
<nowarn>true</nowarn> <!-- Disable warnings -->
<args>
<arg>-Xjsr305=strict</arg> <!-- Enable strict mode for JSR-305 annotations -->
987
...
</args>
</configuration>
</plugin>
<project ...>
<properties>
<kotlin.compiler.languageVersion>1.0</kotlin.compiler.languageVersion>
</properties>
</project>
Attributes
common
to
JVM
and
JS
Attributes
specific
to
JVM
988
Name Property name Description Possible values Default
value
jvmTarget kotlin.compiler.jvmTarget Target version of the generated JVM "1.6" (DEPRECATED), "1.8", "1.8"
bytecode "9", "10", "11", "12", "13", "14",
"15", "16"
Attributes
specific
to
JS
metaInfo Generate .meta.js and .kjsm files with metadata. true, false true
Use to create a library
sourceMapEmbedSources Embed source files into source map "never", "always", "inlining"
"inlining"
moduleKind The kind of JS module generated by the compiler "umd", "commonjs", "umd"
"amd", "plain"
Generating
documentation
The standard JavaDoc generation plugin (maven-javadoc-plugin) does not support Kotlin code. To generate
documentation for Kotlin projects, use Dokka; please refer to the Dokka README for configuration instructions. Dokka
supports mixed-language projects and can generate output in multiple formats, including standard JavaDoc.
OSGi
For OSGi support see the Kotlin OSGi page.
989
Ant
Getting
the
Ant
tasks
Kotlin provides three tasks for Ant:
withKotlin: Task to compile Kotlin files when using the standard javac Ant task
These tasks are defined in the kotlin-ant.jar library which is located in the lib folder in the Kotlin Compiler archive. Ant
version 1.8.2+ is required.
Targeting
JVM
with
Kotlin-only
source
When the project consists of exclusively Kotlin source code, the easiest way to compile the project is to use the kotlinc
task:
<target name="build">
<kotlinc src="hello.kt" output="hello.jar"/>
</target>
</project>
where ${kotlin.lib} points to the folder where the Kotlin standalone compiler was unzipped.
Targeting
JVM
with
Kotlin-only
source
and
multiple
roots
If a project consists of multiple source roots, use src as elements to define paths:
<target name="build">
<kotlinc output="hello.jar">
<src path="root1"/>
<src path="root2"/>
</kotlinc>
</target>
</project>
990
Targeting
JVM
with
Kotlin
and
Java
source
If a project consists of both Kotlin and Java source code, while it is possible to use kotlinc, to avoid repetition of task
parameters, it is recommended to use withKotlin task:
<target name="build">
<delete dir="classes" failonerror="false"/>
<mkdir dir="classes"/>
<javac destdir="classes" includeAntRuntime="false" srcdir="src">
<withKotlin/>
</javac>
<jar destfile="hello.jar">
<fileset dir="classes"/>
</jar>
</target>
</project>
You can also specify the name of the module being compiled as the moduleName attribute:
<withKotlin moduleName="myModule"/>
Targeting
JavaScript
with
single
source
folder
<target name="build">
<kotlin2js src="root1" output="out.js"/>
</target>
</project>
Targeting
JavaScript
with
Prefix,
PostFix
and
sourcemap
options
<target name="build">
<kotlin2js src="root1" output="out.js" outputPrefix="prefix" outputPostfix="postfix"
sourcemap="true"/>
</target>
</project>
991
Targeting
JavaScript
with
single
source
folder
and
metaInfo
option
The metaInfo option is useful, if you want to distribute the result of translation as a Kotlin/JavaScript library. If metaInfo
was set to true, then during compilation additional JS file with binary metadata will be created. This file should be
distributed together with the result of translation:
<target name="build">
<!-- out.meta.js will be created, which contains binary metadata -->
<kotlin2js src="root1" output="out.js" metaInfo="true"/>
</target>
</project>
References
Complete list of elements and attributes are listed below:
Attributes
common
for
kotlinc
and
kotlin2js
noStdlib Does not include the Kotlin standard library into the classpath No false
failOnError Fails the build if errors are detected during the compilation No true
kotlinc
attributes
992
Name Description Required Default Value
moduleName Name of the module being compiled No The name of the target (if specified) or
the project
kotlin2js
attributes
Passing
raw
compiler
arguments
To pass custom raw compiler arguments, you can use <compilerarg> elements with either value or line attributes. This
can be done within the <kotlinc>, <kotlin2js>, and <withKotlin> task elements, as follows:
The full list of arguments that can be used is shown when you run kotlinc -help.
Run
code
snippets
–
tutorial
There may be times when you need to quickly write and execute code outside of a project or application. This may be
993
useful, for example, when learning Kotlin or evaluating expressions. Let's have a look at three handy ways we can use to
run Kotlin code quickly:
Scratches let us write and run code in a temporary file outside of our project in the IDE.
Scratches
and
worksheets
The Kotlin plugin for IntelliJ IDEA supports scratches and worksheets.
Scratches let you create code drafts in the same IDE window with your project and run them on the fly. Scratches are not
tied to projects; you can access and run all your scratches from any IntelliJ IDEA window on your OS.
To create a Kotlin scratch, click File | New | Scratch file and select the Kotlin type.
In turn, worksheets are project files: they are stored in project directories and tied to the project modules. Worksheets are
useful for writing code parts that don't actually make a software unit but should still be stored together in a project. For
example, you can use worksheets for education or demo materials.
To create a Kotlin worksheet in a project directory, right-click the directory in the project tree and select New | Kotlin
Worksheet.
In scratches and worksheets, you can write any valid Kotlin code. Syntax highlighting, auto-completion, and the other
IntelliJ IDEA code editing features are all supported too. Note that there's no need for declaring the main function: all the
code you write is executed as if it would be in the body of main.
Once you have finished writing your code in a scratch or a worksheet, click Run. The execution results will appear in the
lines opposite your code.
Run scratch
994
Interactive
mode
IntelliJ IDEA can run the code from scratches and worksheets automatically. To get the execution results when you stop
typing, switch on the Interactive mode.
Using
modules
We can use classes or functions from a Kotlin project, in our scratches and worksheets.
Worksheets automatically get access to classes and functions from the module where they reside.
To use classes or functions from a project in a scratch, import them into the scratch file as usual with the import
statement. Then write your code and run it with the appropriate module selected in Use classpath of module list.
Both scratches and worksheets use the compiled versions of connected modules. So, if you modify a module's source
files, the changes will propagate to scratches and worksheets when you rebuild the module. To rebuild the module
automatically before each run of a scratch or a worksheet, select Make before Run.
Running
as
REPL
To evaluate each particular expression in a scratch or a worksheet, run it with Use REPL selected. The code will be
executed the same way as in REPL: the code lines will run sequentially, providing results of each call. You can later refer
to the results by the names res* shown in the corresponding lines.
995
Scratch REPL
REPL
REPL (Read-Eval-Print-Loop) is a tool for running Kotlin code interactively. REPL lets you evaluate expressions and code
chunks without creating projects or even functions if you don't need them.
To run REPL in the OS command line, open /bin/kotlinc-jvm from the directory of standalone Kotlin compiler.
The REPL command line interface will open. You can enter any valid Kotlin code and see the result. The results are
printed as variables with auto-generated names like res*. You can later use such variables in the code you run in REPL.
Run REPL
REPL supports multiline input as well. The result of the multiline input is the value of its last expression.
996
REPL multi-line run
Migrate
to
Kotlin
code
style
Kotlin
coding
conventions
and
IntelliJ
IDEA
formatter
Kotlin coding conventions affect several aspects of writing idiomatic Kotlin, and a set of formatting recommendations
aimed at improving Kotlin code readability is among them.
Unfortunately, the code formatter built into IntelliJ IDEA had to work long before this document was released and now has
a default setup that produces different formatting from what is now recommended.
It may seem a logical next step to remove this obscurity by switching the defaults in IntelliJ IDEA and make formatting
consistent with the Kotlin coding conventions. But this would mean that all the existing Kotlin projects will have a new
code style enabled the moment the Kotlin plugin is installed. Not really the expected result for plugin update, right?
Enable the official code style formatting by default starting from Kotlin 1.3 and only for new projects (old formatting can
be enabled manually)
Authors of existing projects may choose to migrate to the Kotlin coding conventions
Authors of existing projects may choose to explicitly declare using the old code style in a project (this way the project
won't be affected by switching to the defaults in the future)
Switch to the default formatting and make it consistent with Kotlin coding conventions in Kotlin 1.4
997
Differences
between
"Kotlin
coding
conventions"
and
"IntelliJ
IDEA
default
code
style"
The most notable change is in the continuation indentation policy. There's a nice idea to use the double indent for
showing that a multi-line expression hasn't ended on the previous line. This is a very simple and general rule, but several
Kotlin constructions look a bit awkward when they are formatted this way. In Kotlin coding conventions, it's
recommended to use a single indent in cases where the long continuation indent has been forced before.
Code formatting
In practice, quite a bit of code is affected, so this can be considered a major code style update.
Migration
to
a
new
code
style
discussion
A new code style adoption might be a very natural process if it starts with a new project, when there's no code formatted
in the old way. That is why starting from version 1.3, the Kotlin IntelliJ Plugin creates new projects with formatting from the
Coding conventions document which is enabled by default.
Changing formatting in an existing project is a far more demanding task, and should probably be started with discussing
all the caveats with the team.
The main disadvantage of changing the code style in an existing project is that the blame/annotate VCS feature will point
to irrelevant commits more often. While each VCS has some kind of way to deal with this problem ("Annotate Previous
Revision" can be used in IntelliJ IDEA), it's important to decide if a new style is worth all the effort. The practice of
separating reformatting commits from meaningful changes can help a lot with later investigations.
Also migrating can be harder for larger teams because committing a lot of files in several subsystems may produce
merging conflicts in personal branches. And while each conflict resolution is usually trivial, it's still wise to know if there
are large feature branches currently in work.
In general, for small projects, we recommend converting all the files at once.
For medium and large projects the decision may be tough. If you are not ready to update many files right away you may
decide to migrate module by module, or continue with gradual migration for modified files only.
998
Migration
to
a
new
code
style
Switching to the Kotlin Coding Conventions code style can be done in Settings | Editor | Code Style | Kotlin dialog. Switch
scheme to Project and activate Set from... | Predefined Style | Kotlin Style Guide.
In order to share those changes for all project developers .idea/codeStyle folder have to be committed to VCS.
If an external build system is used for configuring the project, and it's been decided not to share .idea/codeStyle folder,
Kotlin coding conventions can be forced with an additional property:
In
Gradle
Add kotlin.code.style=official property to the gradle.properties file at the project root and commit the file to VCS.
In
Maven
Add kotlin.code.style official property to root pom.xml project file.
Having the kotlin.code.style option set may modify the code style scheme during a project import and may
change the code style settings.
After updating your code style settings, activate Reformat Code in the project view on the desired scope.
999
Reformat code
For a gradual migration, it's possible to enable the File is not formatted according to project settings inspection. It will
highlight the places that should be reformatted. After enabling the Apply only to modified files option, inspection will show
formatting problems only in modified files. Such files are probably going to be committed soon anyway.
Store
old
code
style
in
project
It's always possible to explicitly set the IntelliJ IDEA code style as the correct code style for the project. To do so, switch
to the Project scheme in Settings | Editor | Code Style | Kotlin and select Kotlin obsolete IntelliJ IDEA codestyle in the Use
defaults from: on the Load tab.
In order to share the changes across the project developers .idea/codeStyle folder, it has to be committed to VCS.
Alternatively, kotlin.code.style = obsolete can be used for projects configured with Gradle or Maven.
Eclipse
IDE
1000
Eclipse IDE is a widely known IDE that offers various packages for development in different languages and for different
platforms. You can use is for writing Kotlin code. On this page, you will learn how to get started with Kotlin in Eclipse IDE.
Set
up
the
environment
First of all, you need the Eclipse IDE installed on your system. You can download its latest version from download page.
The Eclipse IDE for Java Developers bundle is recommended.
To add the Kotlin support to your Eclipse IDE, install the Kotlin Plugin for Eclipse. We recommend installing the Kotlin
plugin from Eclipse Marketplace. Open the Help | Eclipse Marketplace... menu and search for Kotlin Plugin for Eclipse:
Eclipse Marketplace
Once the plugin is installed and Eclipse is restarted, make sure the plugin is installed correctly: open the Kotlin
perspective in the menu Window | Perspective | Open Perspective | Other...
1001
Kotlin Perspective
Create
a
new
project
Now you are ready to create a new Kotlin project.
1002
New Kotlin project
For Eclipse IDE, the project is also a Java project but configured with Kotlin nature, meaning it has the Kotlin Builder and
reference to the Kotlin Runtime Library. Great thing about this solution is that you can add both Kotlin and Java code to
the same project.
1003
Empty Kotlin project
You can enter the name without the .kt extension. Eclipse will add it automatically.
1004
New Kotlin file wizard
Once you have a source file, add the main function - the entry point to a Kotlin application. You can simply type main and
invoke code completion by hitting Ctrl + Space.
1005
Kotlin function example
Run
the
application
To run the application, right-click somewhere in the main file and select Run As | Kotlin Application.
1006
Run Kotlin application
If everything went well, you'll see the result in the Console window.
Congratulations! You now have your Kotlin application running in Eclipse IDE.
1007
Kotlin
command-line
compiler
Every release ships with a standalone version of the compiler. You can download the latest version ( kotlin-compiler-
1.5.31.zip) from GitHub Releases.
Install
the
compiler
Manual
install
Unzip the standalone compiler into a directory and optionally add the bin directory to the system path. The bin directory
contains the scripts needed to compile and run Kotlin on Windows, OS X and Linux.
SDKMAN!
An easier way to install Kotlin on UNIX-based systems such as OS X, Linux, Cygwin, FreeBSD, and Solaris is SDKMAN!. It
also works in Bash and ZSH shells. Learn how to install SDKMAN!.
To install the Kotlin compiler via SDKMAN!, run the following command in a terminal:
Homebrew
Alternatively, on OS X you can install the compiler via Homebrew.
$ brew update
$ brew install kotlin
Snap
package
If you use Snap on Ubuntu 16.04 or later, you can install the compiler from the command line:
Create
and
run
an
application
1. Create a simple application in Kotlin that displays "Hello, World!". In your favorite editor, create a new file called
hello.kt with the following lines:
fun main() {
println("Hello, World!")
1008
}
The -d option indicates the output path for generated class files, which may be either a directory or a .jar file. The -
include-runtime option makes the resulting .jar file self-contained and runnable by including the Kotlin runtime library in
it.
$ kotlinc -help
Compile
a
library
If you're developing a library to be used by other Kotlin applications, you can build the .jar file without including the Kotlin
runtime into it.
Since binaries compiled this way depend on the Kotlin runtime you should make sure the latter is present in the classpath
whenever your compiled library is used.
You can also use the kotlin script to run binaries produced by the Kotlin compiler:
HelloKt is the main class name that the Kotlin compiler generates for the file named hello.kt.
Run
the
REPL
You can run the compiler without parameters to have an interactive shell. In this shell, you can type any valid Kotlin code
and see the results.
1009
Shell
Run
scripts
Kotlin can also be used as a scripting language. A script is a Kotlin source file (.kts) with top-level executable code.
import java.io.File
// Get the passed in path, i.e. "-d some/path" or use the current path.
val path = if (args.contains("-d")) args[1 + args.indexOf("-d")]
else "."
To run a script, we just pass the -script option to the compiler with the corresponding script file.
Since 1.3.0, Kotlin has an experimental support for scripts customization, such as adding external properties, providing
static or dynamic dependencies, and so on. Customizations are defined by so-called Script definitions- annotated kotlin
classes with appropriate support code. The script filename extension is used to select appropriate definition.
Properly prepared script definitions are detected and applied automatically when the appropriate jars are included in the
compilation classpath. Alternatively, you can specify definitions manually using -script-templates option to the compiler:
Kotlin
compiler
options
Each release of Kotlin includes compilers for the supported targets: JVM, JavaScript, and native binaries for supported
platforms.
These compilers are used by the IDE when you click the Compile or Run button for your Kotlin project.
1010
You can also run Kotlin compilers manually from the command line as described in the Working with command-line
compiler tutorial.
Compiler
options
Kotlin compilers have a number of options for tailoring the compiling process. Compiler options for different targets are
listed on this page together with a description of each one.
There are several ways to set the compiler options and their values (compiler arguments):
In IntelliJ IDEA, write in the compiler arguments in the Additional command-line parameters text box in Settings | Build,
Execution, Deployment | Compilers | Kotlin Compiler
If you're using Gradle, specify the compiler arguments in the kotlinOptions property of the Kotlin compilation task. For
details, see Gradle.
If you're using Maven, specify the compiler arguments in the <configuration> element of the Maven plugin node. For
details, see Maven.
If you run a command-line compiler, add the compiler arguments directly to the utility call or write them into an argfile.
For example:
On Windows, when you pass compiler arguments that contain delimiter characters (whitespace, =, ;, ,),
surround these arguments with double quotes (").
Common
options
The following options are common for all Kotlin compilers.
-version
Display the compiler version.
-nowarn
Suppress the compiler from displaying warnings during compilation.
-Werror
1011
Turn any warnings into a compilation error.
-verbose
Enable verbose logging output which includes details of the compilation process.
-script
Evaluate a Kotlin script file. When called with this option, the compiler executes the first Kotlin script (*.kts) file among the
given arguments.
-help
(-h)
Display usage information and exit. Only standard options are shown. To show advanced options, use -X.
-X
Display information about the advanced options and exit. These options are currently unstable: their names and behavior
may be changed without notice.
-kotlin-home
path
Specify a custom path to the Kotlin compiler used for the discovery of runtime libraries.
-P
plugin:pluginId:optionName=value
Pass an option to a Kotlin compiler plugin. Available plugins and their options are listed in the Tools > Compiler plugins
section of the documentation.
-language-version
version
Provide source compatibility with the specified version of Kotlin.
-api-version
version
Allow using declarations only from the specified version of Kotlin bundled libraries.
-progressive
Enable the progressive mode for the compiler.
In the progressive mode, deprecations and bug fixes for unstable code take effect immediately, instead of going through
a graceful migration cycle. Code written in the progressive mode is backwards compatible; however, code written in a
non-progressive mode may cause compilation errors in the progressive mode.
1012
@argfile
Read the compiler options from the given file. Such a file can contain compiler options with values and paths to the
source files. Options and paths should be separated by whitespaces. For example:
If the files reside in locations different from the current directory, use relative paths.
Kotlin/JVM
compiler
options
The Kotlin compiler for JVM compiles Kotlin source files into Java class files. The command-line tools for Kotlin to JVM
compilation are kotlinc and kotlinc-jvm. You can also use them for executing Kotlin script files.
In addition to the common options, Kotlin/JVM compiler has the options listed below.
-classpath
path
(-cp
path)
Search for class files in the specified paths. Separate elements of the classpath with system path separators (; on
Windows, : on macOS/Linux). The classpath can contain file and directory paths, ZIP, or JAR files.
-d
path
Place the generated class files into the specified location. The location can be a directory, a ZIP, or a JAR file.
-include-runtime
Include the Kotlin runtime into the resulting JAR file. Makes the resulting archive runnable on any Java-enabled
environment.
-jdk-home
path
Use a custom JDK home directory to include into the classpath if it differs from the default JAVA_HOME.
-jvm-target
version
Specify the target version of the generated JVM bytecode. Possible values are 1.6 (DEPRECATED), 1.8, 9, 10, 11, 12, 13,
1013
14, 15 and 16. The default value is 1.8.
-java-parameters
Generate metadata for Java 1.8 reflection on method parameters.
-module-name
name
(JVM)
Set a custom name for the generated .kotlin_module file.
-no-jdk
Don't automatically include the Java runtime into the classpath.
-no-reflect
Don't automatically include the Kotlin reflection (kotlin-reflect.jar) into the classpath.
-no-stdlib
(JVM)
Don't automatically include the Kotlin/JVM stdlib (kotlin-stdlib.jar) and Kotlin reflection (kotlin-reflect.jar) into the
classpath.
-script-templates
classnames[,]
Script definition template classes. Use fully qualified class names and separate them with commas (,).
Kotlin/JS
compiler
options
The Kotlin compiler for JS compiles Kotlin source files into JavaScript code. The command-line tool for Kotlin to JS
compilation is kotlinc-js.
In addition to the common options, Kotlin/JS compiler has the options listed below.
-libraries
path
Paths to Kotlin libraries with .meta.js and .kjsm files, separated by the system path separator.
-main
{call|noCall}
Define whether the main function should be called upon execution.
-meta-info
Generate .meta.js and .kjsm files with metadata. Use this option when creating a JS library.
1014
-module-kind
{umd|commonjs|amd|plain}
The kind of JS module generated by the compiler:
To learn more about the different kinds of JS module and the distinctions between them, see this article.
-no-stdlib
(JS)
Don't automatically include the default Kotlin/JS stdlib into the compilation dependencies.
-output
filepath
Set the destination file for the compilation result. The value must be a path to a .js file including its name.
-output-postfix
filepath
Add the content of the specified file to the end of the output file.
-output-prefix
filepath
Add the content of the specified file to the beginning of the output file.
-source-map
Generate the source map.
-source-map-base-dirs
path
Use the specified paths as base directories. Base directories are used for calculating relative paths in the source map.
-source-map-embed-sources
{always|never|inlining}
Embed source files into the source map.
-source-map-prefix
Add the specified prefix to paths in the source map.
Kotlin/Native
compiler
options
1015
Kotlin/Native compiler compiles Kotlin source files into native binaries for the supported platforms. The command-line
tool for Kotlin/Native compilation is kotlinc-native.
In addition to the common options, Kotlin/Native compiler has the options listed below.
-enable-assertions
(-ea)
Enable runtime assertions in the generated code.
-g
Enable emitting debug information.
-generate-test-runner
(-tr)
Produce an application for running unit tests from the project.
-generate-worker-test-runner
(-trw)
Produce an application for running unit tests in a worker thread.
-generate-no-exit-test-runner
(-trn)
Produce an application for running unit tests without an explicit process exit.
-include-binary
path
(-ib
path)
Pack external binary within the generated klib file.
-library
path
(-l
path)
Link with the library. To learn about using libraries in Kotlin/native projects, see Kotlin/Native libraries.
-library-version
version
(-lv
version)
Set the library version.
-list-targets
List the available hardware targets.
-manifest
path
Provide a manifest addend file.
1016
-module-name
name
(Native)
Specify a name for the compilation module. This option can also be used to specify a name prefix for the declarations
exported to Objective-C: How do I specify a custom Objective-C prefix/name for my Kotlin framework?
-native-library
path
(-nl
path)
Include the native bitcode library.
-no-default-libs
Disable linking user code with the default platform libraries distributed with the compiler.
-nomain
Assume the main entry point to be provided by external libraries.
-nopack
Don't pack the library into a klib file.
-linker-option
Pass an argument to the linker during binary building. This can be used for linking against some native library.
-linker-options
args
Pass multiple arguments to the linker during binary building. Separate arguments with whitespaces.
-nostdlib
Don't link with stdlib.
-opt
Enable compilation optimizations.
-output
name
(-o
name)
Set the name for the output file.
-entry
name
(-e
name)
Specify the qualified entry point name.
1017
-produce
output
(-p
output)
Specify output file kind:
program
static
dynamic
framework
library
bitcode
-repo
path
(-r
path)
Library search path. For more information, see Library search sequence.
-target
target
Set hardware target. To see the list of available targets, use the -list-targets option.
All-open
compiler
plugin
Kotlin has classes and their members final by default, which makes it inconvenient to use frameworks and libraries such
as Spring AOP that require classes to be open. The all-open compiler plugin adapts Kotlin to the requirements of those
frameworks and makes classes annotated with a specific annotation and their members open without the explicit open
keyword.
For instance, when you use Spring, you don't need all the classes to be open, but only classes annotated with specific
annotations like @Configuration or @Service. All-open allows to specify such annotations.
We provide all-open plugin support both for Gradle and Maven with the complete IDE integration.
For Spring, you can use the kotlin-spring compiler plugin (see below).
Gradle
Add the plugin artifact to the build script dependencies and apply the plugin:
buildscript {
dependencies {
classpath "org.jetbrains.kotlin:kotlin-allopen:$kotlin_version"
}
1018
}
plugins {
id "org.jetbrains.kotlin.plugin.allopen" version "1.5.31"
}
Then specify the list of annotations that will make classes open:
allOpen {
annotation("com.my.Annotation")
// annotations("com.another.Annotation", "com.third.Annotation")
}
If the class (or any of its superclasses) is annotated with com.my.Annotation, the class itself and all its members will
become open.
@com.my.Annotation
annotation class MyFrameworkAnnotation
@MyFrameworkAnnotation
class MyClass // will be all-open
Maven
Here's how to use all-open with Maven:
<plugin>
<artifactId>kotlin-maven-plugin</artifactId>
<groupId>org.jetbrains.kotlin</groupId>
<version>${kotlin.version}</version>
<configuration>
<compilerPlugins>
<!-- Or "spring" for the Spring support -->
<plugin>all-open</plugin>
</compilerPlugins>
<pluginOptions>
<!-- Each annotation is placed on its own line -->
<option>all-open:annotation=com.my.Annotation</option>
<option>all-open:annotation=com.their.AnotherAnnotation</option>
1019
</pluginOptions>
</configuration>
<dependencies>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-allopen</artifactId>
<version>${kotlin.version}</version>
</dependency>
</dependencies>
</plugin>
Please refer to the Gradle section for the detailed information about how all-open annotations work.
Spring
support
If you use Spring, you can enable the kotlin-spring compiler plugin instead of specifying Spring annotations manually. The
kotlin-spring is a wrapper on top of all-open, and it behaves exactly the same way.
buildscript {
dependencies {
classpath "org.jetbrains.kotlin:kotlin-allopen:$kotlin_version"
}
}
plugins {
id "org.jetbrains.kotlin.plugin.spring" version "1.5.31"
}
In Maven, the spring plugin is provided by the kotlin-maven-allopen plugin dependency, so to enable it:
<compilerPlugins>
<plugin>spring</plugin>
</compilerPlugins>
<dependencies>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-allopen</artifactId>
<version>${kotlin.version}</version>
</dependency>
</dependencies>
1020
@Component
@Async
@Transactional
@Cacheable
@SpringBootTest
Thanks to meta-annotations support, classes annotated with @Configuration, @Controller, @RestController, @Service or
@Repository are automatically opened since these annotations are meta-annotated with @Component.
Of course, you can use both kotlin-allopen and kotlin-spring in the same project.
Note that if you use the project template generated by the start.spring.io service, the kotlin-spring plugin will be enabled
by default.
Command-line
compiler
All-open compiler plugin JAR is available in the binary distribution of the Kotlin compiler. You can attach the plugin by
providing the path to its JAR file using the Xplugin kotlinc option:
-Xplugin=$KOTLIN_HOME/lib/allopen-compiler-plugin.jar
You can specify all-open annotations directly, using the annotation plugin option, or enable the "preset". The only preset
available now for all-open is spring.
-P plugin:org.jetbrains.kotlin.allopen:annotation=com.my.Annotation
-P plugin:org.jetbrains.kotlin.allopen:preset=spring
No-arg
compiler
plugin
The no-arg compiler plugin generates an additional zero-argument constructor for classes with a specific annotation.
The generated constructor is synthetic so it can’t be directly called from Java or Kotlin, but it can be called using
reflection.
This allows the Java Persistence API (JPA) to instantiate a class although it doesn't have the zero-parameter constructor
from Kotlin or Java point of view (see the description of kotlin-jpa plugin below.
1021
Gradle
Add the plugin and specify the list of annotations that must lead to generating a no-arg constructor for the annotated
classes.
buildscript {
dependencies {
classpath "org.jetbrains.kotlin:kotlin-noarg:$kotlin_version"
}
}
plugins {
id "org.jetbrains.kotlin.plugin.noarg" version "1.5.31"
}
noArg {
annotation("com.my.Annotation")
}
Enable invokeInitializers option if you want the plugin to run the initialization logic from the synthetic constructor. By
default, it is disabled.
noArg {
invokeInitializers = true
}
Maven
<plugin>
<artifactId>kotlin-maven-plugin</artifactId>
<groupId>org.jetbrains.kotlin</groupId>
<version>${kotlin.version}</version>
<configuration>
<compilerPlugins>
<!-- Or "jpa" for JPA support -->
<plugin>no-arg</plugin>
</compilerPlugins>
<pluginOptions>
<option>no-arg:annotation=com.my.Annotation</option>
<!-- Call instance initializers in the synthetic constructor -->
<!-- <option>no-arg:invokeInitializers=true</option> -->
1022
</pluginOptions>
</configuration>
<dependencies>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-noarg</artifactId>
<version>${kotlin.version}</version>
</dependency>
</dependencies>
</plugin>
JPA
support
As with the kotlin-spring plugin wrapped on top of all-open, kotlin-jpa is wrapped on top of no-arg. The plugin specifies
@Entity, @Embeddable, and @MappedSuperclass no-arg annotations automatically.
buildscript {
dependencies {
classpath "org.jetbrains.kotlin:kotlin-noarg:$kotlin_version"
}
}
plugins {
id "org.jetbrains.kotlin.plugin.jpa" version "1.5.31"
}
<compilerPlugins>
<plugin>jpa</plugin>
</compilerPlugins>
Command-line
compiler
Add the plugin JAR file to the compiler plugin classpath and specify annotations or presets:
-Xplugin=$KOTLIN_HOME/lib/noarg-compiler-plugin.jar
-P plugin:org.jetbrains.kotlin.noarg:annotation=com.my.Annotation
-P plugin:org.jetbrains.kotlin.noarg:preset=jpa
1023
SAM-with-receiver
compiler
plugin
The sam-with-receiver compiler plugin makes the first parameter of the annotated Java "single abstract method" (SAM)
interface method a receiver in Kotlin. This conversion only works when the SAM interface is passed as a Kotlin lambda,
both for SAM adapters and SAM constructors (see the SAM conversions documentation for more details).
Here is an example:
@SamWithReceiver
public interface TaskRunner {
void run(Task task);
}
println("$name is started")
context.executeTask(this)
println("$name is finished")
}
}
Gradle
The usage is the same to all-open and no-arg, except the fact that sam-with-receiver does not have any built-in presets,
and you need to specify your own list of special-treated annotations.
buildscript {
dependencies {
classpath "org.jetbrains.kotlin:kotlin-sam-with-receiver:$kotlin_version"
}
}
samWithReceiver {
annotation("com.my.SamWithReceiver")
}
Maven
1024
<plugin>
<artifactId>kotlin-maven-plugin</artifactId>
<groupId>org.jetbrains.kotlin</groupId>
<version>${kotlin.version}</version>
<configuration>
<compilerPlugins>
<plugin>sam-with-receiver</plugin>
</compilerPlugins>
<pluginOptions>
<option>
sam-with-receiver:annotation=com.my.SamWithReceiver
</option>
</pluginOptions>
</configuration>
<dependencies>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-sam-with-receiver</artifactId>
<version>${kotlin.version}</version>
</dependency>
</dependencies>
</plugin>
Command-line
compiler
Add the plugin JAR file to the compiler plugin classpath and specify the list of sam-with-receiver annotations:
-Xplugin=$KOTLIN_HOME/lib/sam-with-receiver-compiler-plugin.jar
-P plugin:org.jetbrains.kotlin.samWithReceiver:annotation=com.my.SamWithReceiver
Using
kapt
Annotation processors (see JSR 269) are supported in Kotlin with the kapt compiler plugin.
In a nutshell, you can use libraries such as Dagger or Data Binding in your Kotlin projects.
Please read below about how to apply the kapt plugin to your Gradle/Maven build.
Using
in
Gradle
Apply the kotlin-kapt Gradle plugin:
Kotlin
1025
plugins {
kotlin("kapt") version "1.5.31" }
Groovy
plugins {
id "org.jetbrains.kotlin.kapt" version "1.5.31"
}
Then add the respective dependencies using the kapt configuration in your dependencies block:
Kotlin
dependencies {
kapt("groupId:artifactId:version")
}
Groovy
dependencies {
kapt 'groupId:artifactId:version'
}
If you previously used the Android support for annotation processors, replace usages of the annotationProcessor
configuration with kapt. If your project contains Java classes, kapt will also take care of them.
If you use annotation processors for your androidTest or test sources, the respective kapt configurations are named
kaptAndroidTest and kaptTest. Note that kaptAndroidTest and kaptTest extends kapt, so you can just provide the kapt
dependency and it will be available both for production sources and tests.
Annotation
processor
arguments
Use arguments {} block to pass arguments to annotation processors:
kapt {
arguments {
arg("key", "value")
}
}
1026
Gradle
build
cache
support
The kapt annotation processing tasks are cached in Gradle by default. However, annotation processors run arbitrary code
that may not necessarily transform the task inputs into the outputs, might access and modify the files that are not tracked
by Gradle etc. If the annotation processors used in the build cannot be properly cached, it is possible to disable caching
for kapt entirely by adding the following lines to the build script, in order to avoid false-positive cache hits for the kapt
tasks:
kapt {
useBuildCache = false
}
Improving
the
speed
of
builds
that
use
kapt
Running
kapt
tasks
in
parallel
To improve the speed of builds that use kapt, you can enable the Gradle worker API for kapt tasks. Using the worker API
lets Gradle run independent annotation processing tasks from a single project in parallel, which in some cases
significantly decreases the execution time. However, running kapt with Gradle worker API enabled can result in increased
memory consumption due to parallel execution.
To use the Gradle worker API for parallel execution of kapt tasks, add this line to your gradle.properties file:
kapt.use.worker.api=true
When you use the custom JDK home feature in the Kotlin Gradle plugin, kapt task workers use only process isolation
mode. Note that the kapt.workers.isolation property is ignored.
Caching
for
annotation
processors'
classloaders
Caching for annotation processors' classloaders in kapt is Experimental. It may be dropped or changed at any
time. Use it only for evaluation purposes. We would appreciate your feedback on it in YouTrack.
Caching for annotation processors' classloaders helps kapt perform faster if you run many Gradle tasks consecutively.
To enable this feature, use the following properties in your gradle.properties file:
If you run into any problems with caching for annotation processors, disable caching for them:
1027
# specify annotation processors' full names to disable caching for them
kapt.classloaders.cache.disableForProcessors=[annotation processors full names]
Compile
avoidance
for
kapt
To improve the times of incremental builds with kapt, it can use the Gradle compile avoidance. With compile avoidance
enabled, Gradle can skip annotation processing when rebuilding a project. Particularly, annotation processing is skipped
when:
The changes in dependencies are ABI compatible. For example, the only changes are in method bodies.
However, compile avoidance can't be used for annotation processors discovered in the compile classpath since any
changes in them require running the annotation processing tasks.
Add the annotation processor dependencies to the kapt* configurations manually as described above.
Turn off the discovery of annotation processors in the compile classpath by adding this line to your gradle.properties
file:
kapt.include.compile.classpath=false
Incremental
annotation
processing
kapt supports incremental annotation processing that is enabled by default. Currently, annotation processing can be
incremental only if all annotation processors being used are incremental.
To disable incremental annotation processing, add this line to your gradle.properties file:
kapt.incremental.apt=false
Note that incremental annotation processing requires incremental compilation to be enabled as well.
Java
compiler
options
kapt uses Java compiler to run annotation processors.
Here is how you can pass arbitrary options to javac:
kapt {
javacOptions {
// Increase the max count of errors from annotation processors.
// Default is 100.
option("-Xmaxerrs", 500)
}
1028
}
Non-existent
type
correction
Some annotation processors (such as AutoFactory) rely on precise types in declaration signatures. By default, kapt
replaces every unknown type (including types for the generated classes) to NonExistentClass, but you can change this
behavior. Add the option to the build.gradle file to enable error type inferring in stubs:
kapt {
correctErrorTypes = true
}
Using
in
Maven
Add an execution of the kapt goal from kotlin-maven-plugin before compile:
<execution>
<id>kapt</id>
<goals>
<goal>kapt</goal>
</goals>
<configuration>
<sourceDirs>
<sourceDir>src/main/kotlin</sourceDir>
<sourceDir>src/main/java</sourceDir>
</sourceDirs>
<annotationProcessorPaths>
<!-- Specify your annotation processors here. -->
<annotationProcessorPath>
<groupId>com.google.dagger</groupId>
<artifactId>dagger-compiler</artifactId>
<version>2.9</version>
</annotationProcessorPath>
</annotationProcessorPaths>
</configuration>
</execution>
Please note that kapt is still not supported for IntelliJ IDEA’s own build system. Launch the build from the “Maven
Projects†toolbar whenever you want to re-run the annotation processing.
Using
in
CLI
kapt compiler plugin is available in the binary distribution of the Kotlin compiler.
You can attach the plugin by providing the path to its JAR file using the Xplugin kotlinc option:
-Xplugin=$KOTLIN_HOME/lib/kotlin-annotation-processing.jar
1029
Here is a list of the available options:
classes (required): An output path for the generated class files and resources.
stubs (required): An output path for the stub files. In other words, some temporary directory.
apclasspath (repeatable): A path to the annotation processor JAR. Pass as many apclasspath options as many JARs
you have.
apoptions: A base64-encoded list of the annotation processor options. See AP/javac options encoding for more
information.
javacArguments: A base64-encoded list of the options passed to javac. See AP/javac options encoding for more
information.
processors: A comma-specified list of annotation processor qualified class names. If specified, kapt does not try to
find annotation processors in apclasspath.
aptMode (required)
stubs – only generate stubs needed for annotation processing;
The plugin option format is: -P plugin:<plugin id>:<key>=<value>. Options can be repeated.
An example:
-P plugin:org.jetbrains.kotlin.kapt3:sources=build/kapt/sources
-P plugin:org.jetbrains.kotlin.kapt3:classes=build/kapt/classes
-P plugin:org.jetbrains.kotlin.kapt3:stubs=build/kapt/stubs
-P plugin:org.jetbrains.kotlin.kapt3:apclasspath=lib/ap.jar
-P plugin:org.jetbrains.kotlin.kapt3:apclasspath=lib/anotherAp.jar
-P plugin:org.jetbrains.kotlin.kapt3:correctErrorTypes=true
Generating
Kotlin
sources
kapt can generate Kotlin sources. Just write the generated Kotlin source files to the directory specified by
1030
processingEnv.options["kapt.kotlin.generated"], and these files will be compiled together with the main sources.
Note that kapt does not support multiple rounds for the generated Kotlin files.
AP/Javac
options
encoding
apoptions and javacArguments CLI options accept an encoded map of options.
Here is how you can encode options by yourself:
oos.writeInt(options.size)
for ((key, value) in options.entries) {
oos.writeUTF(key)
oos.writeUTF(value)
}
oos.flush()
return Base64.getEncoder().encodeToString(os.toByteArray())
}
Keeping
Java
compiler's
annotation
processors
By default, kapt runs all annotation processors and disables annotation processing by javac. However, you may need
some of javac's annotation processors working (for example, Lombok).
kapt {
keepJavacAnnotationProcessors = true
}
If you use Maven, you need to specify concrete plugin settings. See this example of settings for the Lombok compiler
plugin.
Lombok
compiler
plugin
The Lombok compiler plugin is Experimental. It may be dropped or changed at any time. Use it only for
evaluation purposes. We would appreciate your feedback on it in YouTrack.
The Kotlin Lombok compiler plugin allows the generation and use of Java's Lombok declarations by Kotlin code in the
1031
same mixed Java/Kotlin module. If you call such declarations from another module, then you don't need to use this plugin
for the compilation of that module.
The Lombok compiler plugin cannot replace Lombok, but it helps Lombok work in mixed Java/Kotlin modules. Thus, you
still need to configure Lombok as usual when using this plugin. Learn more about how to make the plugin seeing
Lombok's config.
Supported
annotations
The plugin supports the following annotations:
@Getter, @Setter
@Data
@With
@Value
We're continuing to work on this plugin. To find out the detailed current state, visit the Lombok compiler plugin's
README.
Currently, we don't have plans to support the @Builder annotation. However, we can consider this if you vote for @Builder
in YouTrack.
Kotlin compiler ignores Lombok annotations if you use them in Kotlin code.
Gradle
Apply the kotlin-plugin-lombok Gradle plugin in the build.gradle(.kts) file:
Kotlin
plugins {
kotlin("plugin.lombok") version "1.5.31"
id("io.freefair.lombok") version "5.3.0"
}
Groovy
plugins {
id 'org.jetbrains.kotlin.plugin.lombok' version '1.5.31'
id 'io.freefair.lombok' version '5.3.0'
}
1032
See this test project with examples of the Lombok compiler plugin in use.
Using
the
Lombok
configuration
file
If you use a Lombok configuration file lombok.config, provide a path to it to the plugin. The path should be relative to the
module's directory. Add the following code to your build.gradle(.kts) file:
Kotlin
kotlinLombok {
lombokConfigurationFile(file("lombok.config"))
}
Groovy
kotlinLombok {
lombokConfigurationFile file("lombok.config")
}
See this test project with examples of the Lombok compiler plugin and lombok.config in use.
Maven
To use the Lombok compiler plugin, add the plugin lombok to the compilerPlugins section and the dependency kotlin-
maven-lombok to the dependencies section. If you use a Lombok configuration file lombok.config, provide a path to it to
the plugin in the pluginOptions. Add the following lines to the pom.xml file:
<plugin>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-plugin</artifactId>
<version>${kotlin.version}</version>
<configuration>
<compilerPlugins>
<plugin>lombok</plugin>
</compilerPlugins>
<pluginOptions>
<option>lombok:config=${project.basedir}/lombok.config</option>
</pluginOptions>
</configuration>
<dependencies>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-lombok</artifactId>
<version>${kotlin.version}</version>
</dependency>
<dependency>
1033
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.20</version>
<scope>provided</scope>
</dependency>
</dependencies>
</plugin>
See this test project example of the Lombok compiler plugin and lombok.config in use.
Using
with
kapt
By default, the kapt compiler plugin runs all annotation processors and disables annotation processing by javac. To run
Lombok along with kapt, set up kapt to keep javac's annotation processors working.
kapt {
keepJavacAnnotationProcessors = true
}
In Maven, use the following settings to launch Lombok with Java's compiler:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<annotationProcessorPaths>
<annotationProcessorPath>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
</annotationProcessorPath>
</annotationProcessorPaths>
</configuration>
</plugin>
The Lombok compiler plugin works correctly with kapt if annotation processors don't depend on the code generated by
Lombok.
Look through the test project examples of kapt and the Lombok compiler plugin in use:
Using Gradle.
Using Maven
1034
Kotlin
Symbol
Processing
API
Kotlin Symbol Processing (KSP) is an API that you can use to develop lightweight compiler plugins. KSP provides a
simplified compiler plugin API that leverages the power of Kotlin while keeping the learning curve at a minimum.
Compared to KAPT, annotation processors that use KSP can run up to 2x faster.
To learn more about how KSP compares to KAPT, check out why KSP. To get started writing a KSP processor, take a
look at the KSP quickstart.
Overview
The KSP API processes Kotlin programs idiomatically. KSP understands Kotlin-specific features, such as extension
functions, declaration-site variance, and local functions. KSP also models types explicitly and provides basic type
checking, such as equivalence and assign-compatibility.
The API models Kotlin program structures at the symbol level according to Kotlin grammar. When KSP-based plugins
process source programs, constructs like classes, class members, functions, and associated parameters are easily
accessible for the processors, while things like if blocks and for loops are not.
Conceptually, KSP is similar to KType in Kotlin reflection. The API allows processors to navigate from class declarations
to corresponding types with specific type arguments and vice-versa. Substituting type arguments, specifying variances,
applying star projections, and marking nullabilities of types are also possible.
Another way to think of KSP is as a pre-processor framework of Kotlin programs. If we refer to KSP-based plugins as
symbol processors, or simply processors, then the data flow in a compilation can be described in the following steps:
3. The Kotlin compiler compiles the source programs together with the generated code.
Unlike a full-fledged compiler plugin, processors cannot modify the code. A compiler plugin that changes language
semantics can sometimes be very confusing. KSP avoids that by treating the source programs as read-only.
How
KSP
looks
at
source
files
Most processors navigate through the various program structures of the input source code. Before diving into usage of
the API, let's look at how a file might look from KSP's point of view:
KSFile
packageName: KSName
fileName: String
annotations: List<KSAnnotation> (File annotations)
declarations: List<KSDeclaration>
KSClassDeclaration // class, interface, object
simpleName: KSName
1035
qualifiedName: KSName
containingFile: String
typeParameters: KSTypeParameter
parentDeclaration: KSDeclaration
classKind: ClassKind
primaryConstructor: KSFunctionDeclaration
superTypes: List<KSTypeReference>
// contains inner classes, member functions, properties, etc.
declarations: List<KSDeclaration>
KSFunctionDeclaration // top level function
simpleName: KSName
qualifiedName: KSName
containingFile: String
typeParameters: KSTypeParameter
parentDeclaration: KSDeclaration
functionKind: FunctionKind
extensionReceiver: KSTypeReference?
returnType: KSTypeReference
parameters: List<KSValueParameter>
// contains local classes, local functions, local variables, etc.
declarations: List<KSDeclaration>
KSPropertyDeclaration // global variable
simpleName: KSName
qualifiedName: KSName
containingFile: String
typeParameters: KSTypeParameter
parentDeclaration: KSDeclaration
extensionReceiver: KSTypeReference?
type: KSTypeReference
getter: KSPropertyGetter
returnType: KSTypeReference
setter: KSPropertySetter
parameter: KSValueParameter
This view lists common things that are declared in the file--classes, functions, properties, and so on.
SymbolProcessorProvider:
The
entry
point
KSP expects an implementation of the SymbolProcessorProvider interface to instantiate SymbolProcessor:
interface SymbolProcessorProvider {
fun create(environment: SymbolProcessorEnvironment): SymbolProcessor
}
interface SymbolProcessor {
fun process(resolver: Resolver): List<KSAnnotated> // Let's focus on this
fun finish() {}
fun onError() {}
}
A Resolver provides SymbolProcessor with access to compiler details such as symbols. A processor that finds all top-
1036
level functions and non-local functions in top-level classes might look something like this:
Resources
Quickstart
Examples
FAQ
Supported
libraries
The table below includes a list of popular libraries on Android and their various stages of support for KSP. If your library is
1037
missing, please feel free to submit a pull request.
Room Experimentally
supported
Moshi Experimentally
supported
Kotshi Experimentally
supported
Lyricist Experimentally
supported
KSP
quickstart
Get a sample processor to check out.
Create
a
processor
of
your
own
1. Create an empty gradle project.
2. Specify version 1.5.30 of the Kotlin plugin in the root project for use in other project modules:
plugins {
kotlin("jvm") version "1.5.30" apply false
}
buildscript {
dependencies {
classpath(kotlin("gradle-plugin", version = "1.5.30"))
}
}
1038
3. Add a module for hosting the processor.
plugins {
kotlin("jvm")
}
repositories {
mavenCentral()
}
dependencies {
implementation("com.google.devtools.ksp:symbol-processing-api:1.5.30-1.0.0-beta09")
}
Use resolver.getSymbolsWithAnnotation() to get the symbols you want to process, given the fully-qualified name of an
annotation.
For sample implementations of the SymbolProcessorProvider and SymbolProcessor interfaces, see the following files
in the sample project.
src/main/kotlin/BuilderProcessor.kt
src/main/kotlin/TestProcessor.kt
After writing your own processor, register your processor provider to the package by including its fully-qualified name
in resources/META-INF/services/com.google.devtools.ksp.processing.SymbolProcessorProvider.
Use
your
own
processor
in
a
project
Setup
using
Kotlin
DSL
1039
1. Create another module that contains a workload where you want to try out your processor.
pluginManagement {
repositories {
gradlePluginPortal()
}
}
3. Run ./gradlew build. You can find the generated code under build/generated/source/ksp.
plugins {
id("com.google.devtools.ksp") version "1.5.30-1.0.0-beta09"
kotlin("jvm")
}
version = "1.0-SNAPSHOT"
repositories {
mavenCentral()
}
dependencies {
implementation(kotlin("stdlib-jdk8"))
implementation(project(":test-processor"))
ksp(project(":test-processor"))
}
Setup
using
Groovy
1. Create another module that contains a workload where you want to try out your processor.
pluginManagement {
repositories {
gradlePluginPortal()
}
}
2. In your projects build.gradle file add a plugins block containing the ksp plugin:
plugins {
id "com.google.devtools.ksp" version "1.5.30-1.0.0-beta09"
}
1040
Apply the com.google.devtools.ksp plugin:
dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
implementation project(":test-processor")
ksp project(":test-processor")
}
Pass
Options
to
Processors
Processor options in SymbolProcessorEnvironment.options are specified in gradle build scripts:
ksp {
arg("option1", "value1")
arg("option2", "value2")
...
}
Make
IDE
Aware
Of
Generated
Code
By default, IntelliJ or other IDEs don't know about the generated code and therefore references to those generated
symbols will be marked unresolvable. To make, for example, IntelliJ be able to reason about the generated symbols, the
following paths need to be marked as generated source root:
build/generated/ksp/main/kotlin/
build/generated/ksp/main/java/
build/generated/ksp/main/resources/
It may also be necessary to configure these directories in your KSP consumer module build.gradle.kts:
kotlin {
sourceSets.main {
kotlin.srcDir("build/generated/ksp/main/kotlin")
}
sourceSets.test {
kotlin.srcDir("build/generated/ksp/test/kotlin")
}
}
1041
Why
KSP
Compiler plugins are powerful metaprogramming tools that can greatly enhance how you write code. Compiler plugins
call compilers directly as libraries to analyze and edit input programs. These plugins can also generate output for various
uses. For example, they can generate boilerplate code, and they can even generate full implementations for specially-
marked program elements, such as Parcelable. Plugins have a variety of other uses and can even be used to implement
and fine-tune features that are not provided directly in a language.
While compiler plugins are powerful, this power comes at a price. To write even the simplest plugin, you need to have
some compiler background knowledge, as well as a certain level of familiarity with the implementation details of your
specific compiler. Another practical issue is that plugins are often closely tied to specific compiler versions, meaning you
might need to update your plugin each time you want to support a newer version of the compiler.
KSP
makes
creating
lightweight
compiler
plugins
easier
KSP is designed to hide compiler changes, minimizing maintenance efforts for processors that use it. KSP is designed not
to be tied to the JVM so that it can be adapted to other platforms more easily in the future. KSP is also designed to
minimize build times. For some processors, such as Glide, KSP reduces full compilation times by up to 25% when
compared to KAPT.
KSP is itself implemented as a compiler plugin. There are prebuilt packages on Google's Maven repository that you can
download and use without having to build the project yourself.
Comparison
to
kotlinc
compiler
plugins
kotlinc compiler plugins have access to almost everything from the compiler and therefore have maximum power and
flexibility. On the other hand, because these plugins can potentially depend on anything in the compiler, they are sensitive
to compiler changes and need to be maintained frequently. These plugins also require a deep understanding of kotlinc
’s implementation, so the learning curve can be steep.
KSP aims to hide most compiler changes through a well-defined API, though major changes in compiler or even the Kotlin
language might still require to be exposed to API users.
KSP tries to fulfill common use cases by providing an API that trades power for simplicity. Its capability is a strict subset
of a general kotlinc plugin. For example, while kotlinc can examine expressions and statements and can even modify
code, KSP cannot.
While writing a kotlinc plugin can be a lot of fun, it can also take a lot of time. If you aren't in a position to learn kotlinc
’s implementation and do not need to modify source code or read expressions, KSP might be a good fit.
Comparison
to
reflection
1042
KSP's API looks similar to kotlin.reflect. The major difference between them is that type references in KSP need to be
resolved explicitly. This is one of the reasons why the interfaces are not shared.
Comparison
to
KAPT
KAPT is a remarkable solution which makes a large amount of Java annotation processors work for Kotlin programs out-
of-box. The major advantages of KSP over KAPT are improved build performance, not tied to JVM, a more idiomatic
Kotlin API, and the ability to understand Kotlin-only symbols.
To run Java annotation processors unmodified, KAPT compiles Kotlin code into Java stubs that retain information that
Java annotation processors care about. To create these stubs, KAPT needs to resolve all symbols in the Kotlin program.
The stub generation costs roughly 1/3 of a full kotlinc analysis and the same order of kotlinc code-generation. For many
annotation processors, this is much longer than the time spent in the processors themselves. For example, Glide looks at
a very limited number of classes with a predefined annotation, and its code generation is fairly quick. Almost all of the
build overhead resides in the stub generation phase. Switching to KSP would immediately reduce the time spent in the
compiler by 25%.
For performance evaluation, we implemented a simplified version of Glide in KSP to make it generate code for the
Tachiyomi project. While the total Kotlin compilation time of the project is 21.55 seconds on our test device, it took 8.67
seconds for KAPT to generate the code, and it took 1.15 seconds for our KSP implementation to generate the code.
Unlike KAPT, processors in KSP do not see input programs from Java's point of view. The API is more natural to Kotlin,
especially for Kotlin-specific features such as top-level functions. Because KSP doesn't delegate to javac like KAPT, it
doesn't assume JVM-specific behaviors and can be used with other platforms potentially.
Limitations
While KSP tries to be a simple solution for most common use cases, it has made several trade-offs compared to other
plugin solutions. The following are not goals of KSP:
We are also exploring several additional features. Note that these features are currently unavailable:
IDE integration: Currently IDEs know nothing about the generated code.
KSP
examples
Get all member functions that are declared directly within a class:
1043
fun KSClassDeclaration.getDeclaredFunctions(): List<KSFunctionDeclaration> {
return this.declarations.filterIsInstance<KSFunctionDeclaration>()
}
Find the actual class or interface declaration that the alias points to recursively:
// @file:kotlin.Suppress("Example1", "Example2")
fun KSFile.suppressedNames(): List<String> {
val ignoredNames = mutableListOf<String>()
annotations.forEach {
if (it.shortName.asString() == "Suppress" &&
it.annotationType.resolve()?.declaration?.qualifiedName?.asString() == "kotlin.Suppress") {
it.arguments.forEach {
(it.value as List<String>).forEach { ignoredNames.add(it) }
}
}
}
return ignoredNames
}
How
KSP
models
Kotlin
code
The API definition can be found here. The diagram below is an overview of how Kotlin is modeled in KSP:
1044
KSNode
accept(KSVisitor<D, R>, D) R
location Location
origin Origin
parent KSNode?
KSAnnotation KSExpectActual
annotationType KSTypeReference findActuals() Sequence<KSDeclaration>
KSReferenceElement KSModifierListOwner KSAnnotated
arguments List<KSValueArgument> findExpects() Sequence<KSDeclaration>
typeArguments List<KSTypeArgument> modifiers Set<Modifier> annotations Sequence<KSAnnotation>
shortName KSName actual Boolean
useSiteTarget AnnotationUseSiteTarget? expect Boolean
KSValueParameter
KSDeclaration
crossInline Boolean
containingFile KSFile?
KSCallableReference hasDefault Boolean
KSClassifierReference docString String? KSValueArgument
accept(KSVisitor<D, R>, D) R KSTypeReference name KSName? KSTypeArgument
accept(KSVisitor<D, R>, D) R KSParenthesizedReference KSPropertyAccessor packageName KSName name KSName? KSDeclarationContainer
KSDynamicReference functionParameters List<KSValueParameter> resolve() KSType noInline Boolean type KSTypeReference?
referencedName() String element KSReferenceElement receiver KSPropertyDeclaration parentDeclaration KSDeclaration? spread Boolean declarations Sequence<KSDeclaration>
receiverType KSTypeReference? element KSReferenceElement? type KSTypeReference variance Variance
qualifier KSClassifierReference? qualifiedName KSName? value Object?
returnType KSTypeReference val Boolean
simpleName KSName
var Boolean
typeParameters List<KSTypeParameter>
vararg Boolean
KSPropertyDeclaration KSClassDeclaration
asMemberOf(KSType) KSType KSFunctionDeclaration asStarProjectedType() KSType
findOverridee() KSPropertyDeclaration? asMemberOf(KSType) KSFunction asType(List<KSTypeArgument>) KSType
KSTypeParameter
delegated Boolean findOverridee() KSDeclaration? allFunctions Sequence<KSFunctionDeclaration> KSFile
bounds Sequence<KSTypeReference> KSTypeAlias
KSPropertySetter KSPropertyGetter extensionReceiver KSTypeReference? abstract Boolean allProperties Sequence<KSPropertyDeclaration> fileName String
name KSName name KSName
parameter KSValueParameter returnType KSTypeReference? getter KSPropertyGetter? extensionReceiver KSTypeReference? classKind ClassKind filePath String
reified Boolean type KSTypeReference
hasBackingField Boolean functionKind FunctionKind companionObject Boolean packageName KSName
variance Variance
mutable Boolean parameters List<KSValueParameter> primaryConstructor KSFunctionDeclaration?
setter KSPropertySetter? returnType KSTypeReference? sealedSubclasses Sequence<KSClassDeclaration>
type KSTypeReference superTypes Sequence<KSTypeReference>
KSVisitorVoid KSType AnnotationUseSiteTarget ClassKind Location Visibility FunctionKind Variance Origin KSFunction Nullability KSName
KSVisitorVoid() isAssignableFrom(KSType) Boolean AnnotationUseSiteTarget() ClassKind(String) Location() Visibility() FunctionKind() Variance(String) Origin() error Boolean Nullability() asString() String
visitAnnotated(KSAnnotated, Unit) Unit makeNotNullable() KSType DELEGATE AnnotationUseSiteTarget ANNOTATION_CLASS ClassKind INTERNAL Visibility ANONYMOUS FunctionKind CONTRAVARIANT Variance JAVA Origin extensionReceiverType KSType? NOT_NULL Nullability qualifier String
visitAnnotation(KSAnnotation, Unit) Unit makeNullable() KSType FIELD AnnotationUseSiteTarget CLASS ClassKind JAVA_PACKAGE Visibility LAMBDA FunctionKind COVARIANT Variance JAVA_LIB Origin parameterTypes List<KSType> NULLABLE Nullability shortName String
visitCallableReference(KSCallableReference, Unit) Unit replace(List<KSTypeArgument>) KSType FILE AnnotationUseSiteTarget ENUM_CLASS ClassKind LOCAL Visibility MEMBER FunctionKind INVARIANT Variance KOTLIN Origin returnType KSType? PLATFORM Nullability
data FileLocation
visitClassDeclaration(KSClassDeclaration, Unit) Unit starProjection() KSType GET AnnotationUseSiteTarget ENUM_ENTRY ClassKind PRIVATE Visibility STATIC FunctionKind STAR Variance KOTLIN_LIB Origin typeParameters List<KSTypeParameter>
FileLocation(String, Int)
visitClassifierReference(KSClassifierReference, Unit) Unit annotations Sequence<KSAnnotation> PARAM AnnotationUseSiteTarget INTERFACE ClassKind NonExistLocation PROTECTED Visibility TOP_LEVEL FunctionKind label String SYNTHETIC Origin
filePath String
visitDeclaration(KSDeclaration, Unit) Unit arguments List<KSTypeArgument> PROPERTY AnnotationUseSiteTarget OBJECT ClassKind PUBLIC Visibility
lineNumber Int
visitDeclarationContainer(KSDeclarationContainer, Unit) Unit covarianceFlexible Boolean RECEIVER AnnotationUseSiteTarget type String
visitDynamicReference(KSDynamicReference, Unit) Unit declaration KSDeclaration SET AnnotationUseSiteTarget
visitFile(KSFile, Unit) Unit error Boolean SETPARAM AnnotationUseSiteTarget
visitFunctionDeclaration(KSFunctionDeclaration, Unit) Unit functionType Boolean
visitModifierListOwner(KSModifierListOwner, Unit) Unit markedNullable Boolean
visitNode(KSNode, Unit) Unit mutabilityFlexible Boolean
visitParenthesizedReference(KSParenthesizedReference, Unit) Unit nullability Nullability
visitPropertyAccessor(KSPropertyAccessor, Unit) Unit suspendFunctionType Boolean
visitPropertyDeclaration(KSPropertyDeclaration, Unit) Unit
visitPropertyGetter(KSPropertyGetter, Unit) Unit
visitPropertySetter(KSPropertySetter, Unit) Unit
visitReferenceElement(KSReferenceElement, Unit) Unit
visitTypeAlias(KSTypeAlias, Unit) Unit
visitTypeArgument(KSTypeArgument, Unit) Unit
visitTypeParameter(KSTypeParameter, Unit) Unit
visitTypeReference(KSTypeReference, Unit) Unit
visitValueArgument(KSValueArgument, Unit) Unit
visitValueParameter(KSValueParameter, Unit) Unit
class diagram
Type
and
resolution
In KSP, references to types are designed to be resolved by processors explicitly (with a few exceptions) because most of
the cost of the underlying API implementation is in resolution. When a type is referenced, such as
KSFunctionDeclaration.returnType or KSAnnotation.annotationType, it is always a KSTypeReference, which is a
KSReferenceElement with annotations and modifiers.
A KSTypeReference can be resolved to a KSType, which refers to a type in Kotlin's type system.
A KSTypeReference has a KSReferenceElement, which models Kotlin‘s program structure: namely, how the reference
is written. It corresponds to the type element in Kotlin's grammar.
If the original declaration referenced by a KSTypeReference is needed, it can usually be found by resolving to KSType and
accessing through KSType.declaration. Moving from where a type is mentioned to where its class is defined looks like
this:
1045
Type resolution is costly and is therefore made explicit. Some of the information obtained from resolution is already
available in KSReferenceElement. For example, KSClassifierReference.referencedName can filter out a lot of elements
that are not interesting. You should resolve type only if you need specific information from KSDeclaration or KSType.
Note that a KSTypeReference pointing to a function type has most of its information in its element. Although it can be
resolved to the family of Function0, Function1, and so on, these resolutions don‘t bring any more information than
KSCallableReference. One use case for resolving function type references is dealing with the identity of the function's
prototype.
Java
annotation
processing
to
KSP
reference
Program
elements
AnnotationMirror KSAnnotation
AnnotationValue KSValueArguments
ExecutableElement KSFunctionDeclaration
Parameterizable KSDeclaration
QualifiedNameable KSDeclaration
TypeElement KSClassDeclaration
TypeParameterElement KSTypeParameter
Types
Because KSP requires explicit type resolution, some functionalities in Java can only be carried out by KSType and the
corresponding elements before resolution.
1046
Java Closest facility in KSP Notes
ArrayType KSBuiltIns.arrayType
DeclaredType KSType /
KSClassifierReference
ErrorType KSType.isError
ExecutableType KSType /
KSCallableReference
IntersectionType KSType /
KSTypeParameter
ReferenceType KSTypeReference
TypeMirror KSType
TypeVariable KSTypeParameter
UnionType N / A Kotlin has only one type per catch block. UnionType is also not observable by even
Java annotation processors.
WildcardType KSType /
KSTypeArgument
Misc
Name KSName
Modifier Modifier
1047
Java Closest facility in KSP notes
AnnotationValueVisitor
ElementVisitor KSVisitor
AnnotatedConstruct KSAnnotated
TypeVisitor
ElementFilter Collection.filterIsInstance
ElementKindVisitor KSVisitor
ElementScanner KSTopDownVisitor
SimpleElementVisitor KSVisitor
SimpleTypeVisitor
TypeKindVisitor
Types Resolver / utils Some of the utils are also integrated into symbol interfaces
Details
How functionalities of Java annotation processing API can be carried out by KSP.
AnnotationMirror
getAnnotationType ksAnnotation.annotationType
1048
Java KSP equivalent
getElementValues ksAnnotation.arguments
AnnotationValue
getValue ksValueArgument.value
Element
getAnnotation // To be implemented.
getAnnotationMirrors ksDeclaration.annotations
getEnclosedElements ksDeclarationContainer.declarations
getEnclosingElements ksDeclaration.parentDeclaration
getModifiers ksDeclaration.modifiers
getSimpleName ksDeclaration.simpleName
ExecutableElement
getDefaultValue // To be implemented.
getParameters ksFunctionDeclaration.parameters
1049
Java KSP equivalent
getReceiverType ksFunctionDeclaration.parentDeclaration
getReturnType ksFunctionDeclaration.returnType
getSimpleName ksFunctionDeclaration.simpleName
getTypeParameters ksFunctionDeclaration.typeParameters
isVarArgs ksFunctionDeclaration.parameters.any
Parameterizable
getTypeParameters ksFunctionDeclaration.typeParameters
QualifiedNameable
getQualifiedName ksDeclaration.qualifiedName
TypeElement
getEnclosedElements ksClassDeclaration.declarations
getEnclosingElement ksClassDeclaration.parentDeclaration
1050
Java KSP equivalent
getQualifiedName ksClassDeclaration.qualifiedName
getSimpleName ksClassDeclaration.simpleName
getTypeParameters ksClassDeclaration.typeParameters
TypeParameterElement
getBounds ksTypeParameter.bounds
getEnclosingElement ksTypeParameter.parentDeclaration
getGenericElement ksTypeParameter.parentDeclaration
VariableElement
getConstantValue // To be implemented.
getEnclosingElement ksValueParameter.parentDeclaration
getSimpleName ksValueParameter.simpleName
ArrayType
getComponentType ksType.arguments.first()
1051
DeclaredType
asElement ksType.declaration
getEnclosingType ksType.declaration.parentDeclaration
getTypeArguments ksType.arguments
ExecutableType
Note: A KSType for a function is just a signature represented by the FunctionN<R, T1, T2, ..., TN> family.
getReceiverType ksFunctionDeclaration.parentDeclaration.asType(...)
getReturnType ksType.declaration.typeParameters.last()
getTypeVariables ksFunctionDeclaration.typeParameters
IntersectionType
getBounds ksTypeParameter.bounds
TypeMirror
getKind // Compare with types in KSBuiltIns for primitive types, Unit type, otherwise declared types
1052
TypeVariable
asElement ksType.declaration
getLowerBound // To be decided. Only needed if capture is provided and explicit bound checking is needed.
getUpperBound ksTypeParameter.bounds
WildcardType
Elements
getAllAnnotationMirrors KSDeclarations.annotations
getDocComment // To be implemented
getElementValuesWithDefaults // To be implemented.
getName resolver.getKSNameFromString
getPackageElement Package not supported, while package information can be retrieved, operation on package is
not possible for KSP
1053
Java KSP equivalent
getTypeElement Resolver.getClassDeclarationByName
hides // To be implemented
isDeprecated KsDeclaration.annotations.any {
it.annotationType.resolve()!!.declaration.quailifiedName!!.asString() ==
Deprecated::class.quailifiedName }
Types
asElement ksType.declaration
asMemberOf resolver.asMemberOf
capture // To be decided.
contains KSType.isAssignableFrom
erasure ksType.starProjection()
getArrayType ksBuiltIns.arrayType.replace(...)
getDeclaredType ksClassDeclaration.asType
1054
Java KSP equivalent
isAssignable ksType.isAssignableFrom
isSameType ksType.equals
isSubtype ksType.isAssignableFrom
Incremental
processing
Incremental processing is a processing technique that avoids re-processing of sources as much as possible. The primary
goal of incremental processing is to reduce the turn-around time of a typical change-compile-test cycle. For general
information, see Wikipedia's article on incremental computing.
To determine which sources are dirty (i.e., those that need to be reprocessed), KSP needs processors' help to identify
which input sources correspond to which generated outputs. To help with this often cumbersome and error-prone
process, KSP is designed to require only a minimal set of root sources that processors use as starting points to navigate
the code structure. In other words, a processor needs to associate an output with the sources of the corresponding
KSNode if the KSNode is obtained from any of the following:
Resolver.getAllFiles
Resolver.getSymbolsWithAnnotation
Resolver.getClassDeclarationByName
Resolver.getDeclarationsFromPackage
Currently, only changes in Kotlin and Java sources are tracked. Changes to the classpath, namely to other modules or
libraries, trigger a full re-processing of all sources by default. To track changes in classpath, set the Gradle property
ksp.incremental.intermodule=true for an experimental implementation on JVM.
Incremental processing is currently enabled by default. To disable it, set the Gradle property ksp.incremental=false. To
enable logs that dump the dirty set according to dependencies and outputs, use ksp.incremental.log=true. These log files
can be found in the build output folder with a .log file extension.
Aggregating
vs
Isolating
1055
Similar to the concepts in Gradle annotation processing, KSP supports both aggregating and isolating modes. Note that
unlike Gradle annotation processing, KSP categorizes each output as either aggregating or isolating, rather than the entire
processor.
An aggregating output can potentially be affected by any input changes, with the exception of removing files that don't
affect other files. This means that any input change results in a rebuild of all aggregating outputs, which in turn means
that all of the corresponding registered, new, and modified source files are reprocessed.
As an example, an output that collects all symbols with a particular annotation is considered an aggregating output.
An isolating output depends only on its specified sources. Changes to other sources do not affect an isolating output.
Note that unlike Gradle annotation processing, you can define multiple source files for a given output.
To summarize, if an output might depend on new or any changed sources, it is considered aggregating. Otherwise, the
output is isolating.
In an isolating Java annotation processor, all the outputs are isolating in KSP.
In an aggregating Java annotation processor, some outputs can be isolating and some be aggregating in KSP.
Example
1
A processor generates outputForA after reading class A in A.kt and class B in B.kt, where A extends B. The processor got
A by Resolver.getSymbolsWithAnnotation and then got B by KSClassDeclaration.superTypes from A. Because the
inclusion of B is due to A, B.kt doesn't need to be specified in dependencies for outputForA. You can still specify B.kt in
this case, but it is unnecessary.
// A.kt
@Interesting
class A : B()
// B.kt
open class B
// Example1Processor.kt
class Example1Processor : SymbolProcessor {
...
override fun process(resolver: Resolver) {
val declA = resolver.getSymbolsWithAnnotation("Interesting").first() as
KSClassDeclaration
val declB = declA.superTypes.first().resolve().declaration
// B.kt isn't required, because it is able to be deduced as a dependency by KSP.
val dependencies = Dependencies(aggregating = true, declA.containingFile!!)
// outputForA.kt
val outputName = "outputFor${declA.simpleName.asString()}"
// outputForA depends on A.kt and B.kt.
val output = codeGenerator.createNewFile(dependencies, "com.example", outputName, "kt")
output.write("// $declA : $declB\n".toByteArray())
1056
output.close()
}
...
}
Example
2
Consider sourceA -> outputA, sourceB -> outputB.
If outputB is aggregating
Both sourceA and sourceB are reprocessed
If outputB is isolating
Only sourceA is reprocessed.
If outputB is aggregating
Both sourceC and sourceB are reprocessed
If outputB is isolating
Only sourceC is reprocessed.
How
file
dirtiness
is
determined
A dirty file is either directly changed by users or indirectly affected by other dirty files. KSP propagates dirtiness in two
steps:
Propagation by resolution tracing: Resolving a type reference (implicitly or explicitly) is the only way to navigate from
one file to another. When a type reference is resolved by a processor, a changed or affected file that contains a
change that may potentially affect the resolution result will affect the file containing that reference.
Propagation by input-output correspondence: If a source file is changed or affected, all other source files having some
output in common with that file are affected.
Note that both of them are transitive and the second forms equivalence classes.
1057
Reporting
bugs
To report a bug, please set Gradle properties ksp.incremental=true and ksp.incremental.log=true, and perform a clean
build. This build produces two log files:
build/kspCaches/<source set>/logs/kspDirtySet.log
build/kspCaches/<source set>/logs/kspSourceToOutputs.log
You can then run successive incremental builds, which will generate two additional log files:
build/kspCaches/<source set>/logs/kspDirtySetByDeps.log
build/kspCaches/<source set>/logs/kspDirtySetByOutputs.log
These logs contain file names of sources and outputs, plus the timestamps of the builds.
Multiple
round
processing
KSP supports multiple round processing, or processing files over multiple rounds, with output from previous rounds being
used as additional input for subsequent rounds.
Changes
to
your
processor
To use multiple round processing, the SymbolProcessor.process() function needs to return a list of deferred symbols
(List<KSAnnotated>) for invalid symbols. Use KSAnnotated.validate() to filter invalid symbols to be deferred to the next
round.
The following sample code shows how to defer invalid symbols by using a validation check:
Multiple
round
behavior
Defer
symbols
to
the
next
round
Processors can defer the processing of certain symbols to the next round. When you defer a symbol, you're waiting for
other processors to provide additional information, and you can continue deferring the symbol as much as needed. Once
1058
the other processors provide the required information, the processor can then process the symbol. You should only defer
invalid symbols which are lacking necessary information. Therefore deferring symbols from classpath is not possible and
will be filtered out by KSP.
As an example, a processor that creates a builder for an annotated class might require all parameter types of its
constructors to be valid (i.e. resolves to a concrete type). In the first round, one of the parameter type is not resolvable.
Then in the second round, it became resolvable because of the generated files from first round.
Validate
symbols
A convenient way to decide if a symbol should be deferred is through validation. A processor should know which
information is necessary to properly process the symbol. Note that validation usually requires resolution which can be
expensive, so we recommend checking only what is required. Continuing with the previous example, an ideal validation
for the builder processor checks only whether all resolved parameter types of the constructors of annotated symbols
contain isError == false.
KSP provides a default validation utility. For more information, see the Advanced section.
Termination
condition
Multiple round processing terminates when a full round of processing generates no new files. If unprocessed deferred
symbols still exist when the termination condition is met, KSP logs an error message for each processor with
unprocessed deferred symbols.
Files
accessible
at
each
round
Both newly generated files and existing files are accessible through a Resolver. KSP provides two APIs for accessing files:
Resolver.getAllFiles() and Resolver.getNewFiles. getAllFiles returns a combined list of both existing files and newly
generated files, while getNewFiles returns only newly generated files.
Changes
to
getSymbolsAnnotatedWith
To avoid unnecessary reprocessing of symbols, getSymbolsAnnotatedWith returns only those symbols found in newly
generated files.
Processor
instantiating
A processor instance is created only once, which means you can store information in the processor object to be used for
later rounds.
Information
consistent
cross
rounds
All KSP symbols will not be reusable across multiple rounds, as the resolution result can potentially change based on
what was generated in a previous round. However, since KSP does not allow modifying existing code, some information
such as the string value for a symbol name should still be reusable. To summarize, processors can store information from
previous rounds but need to bear in mind that this information might be invalid in future rounds.
1059
Error
and
Exception
Handling
When an error (defined by processor calling KSPLogger.error()) or exception occurs, processing stops after the current
round completes. All processors will call the onError() method and will not call the finish() method.
Note that even though an error has occurred, other processors continue processing normally for that round. This means
that error handling occurs after processing has completed for the round.
Upon Exceptions, KSP will try to distinguish the exceptions from KSP and exceptions from processors. Exceptions will
result in a termination of processing immediately and be logged as an error in KSPLogger. Exceptions from KSP should
be reported to KSP developers for further investigation. At the end of the round where exceptions or errors happened, all
processors will invoke onError() function to do their own error handling.
KSP provides a default no-op implementation for onError() as part of the SymbolProcessor interface. You can override
this method to provide your own error handling logic.
Advanced
Default
behavior
for
validation
The default validation logic provided by KSP validates all directly reachable symbols inside the enclosing scope of the
symbol that is being validated. Default validation checks whether references in the enclosed scope are resolvable to a
concrete type but does not recursively dive into the referenced types to perform validation.
Write
your
own
validation
logic
Default validation behavior might not be suitable for all cases. You can reference KSValidateVisitor and write your own
validation logic by providing a custom predicate lambda, which is then used by KSValidateVisitor to filter out symbols that
need to be checked.
Frequently
asked
questions
Why
KSP?
KSP has several advantages over KAPT:
It is faster.
1060
Why
is
KSP
faster
than
KAPT?
KAPT has to parse and resolve every type reference in order to generate Java stubs, whereas KSP resolves references
on-demand. Delegating to javac also takes time.
Additionally, KSP’s incremental processing model has a finer granularity than just isolating and aggregating. It finds
more opportunities to avoid reprocessing everything. Also, because KSP traces symbol resolutions dynamically, a change
in a file is less likely to pollute other files and therefore the set of files to be reprocessed is smaller. This is not possible for
KAPT because it delegates processing to javac.
Is
KSP
Kotlin-specific?
KSP can process Java sources as well. The API is unified, meaning that when you parse a Java class and a Kotlin class
you get a unified data structure in KSP.
Kotlin
and
continuous
integration
with
TeamCity
On this page, you'll learn how to set up TeamCity to build your Kotlin project. For more information and basics of
TeamCity please check the Documentation page which contains information about installation, basic configuration, etc.
Kotlin works with different build tools, so if you're using a standard tool such as Ant, Maven or Gradle, the process for
setting up a Kotlin project is no different to any other language or library that integrates with these tools. Where there are
some minor requirements and differences is when using the internal build system of IntelliJ IDEA, which is also supported
on TeamCity.
Gradle,
Maven,
and
Ant
If using Ant, Maven or Gradle, the setup process is straightforward. All that is needed is to define the Build Step. For
example, if using Gradle, simply define the required parameters such as the Step Name and Gradle tasks that need
executing for the Runner Type.
1061
Gradle Build Step
Since all the dependencies required for Kotlin are defined in the Gradle file, nothing else needs to be configured
specifically for Kotlin to run correctly.
If using Ant or Maven, the same configuration applies. The only difference being that the Runner Type would be Ant or
Maven respectively.
IntelliJ
IDEA
Build
System
If using IntelliJ IDEA build system with TeamCity, make sure that the version of Kotlin being used by IntelliJ IDEA is the
same as the one that TeamCity runs. You may need to download the specific version of the Kotlin plugin and install it on
TeamCity.
Fortunately, there is a meta-runner already available that takes care of most of the manual work. If not familiar with the
concept of TeamCity meta-runners, check the documentation. They are very easy and powerful way to introduce custom
Runners without the need to write plugins.
Download
and
install
the
meta-runner
The meta-runner for Kotlin is available on GitHub. Download that meta-runner and import it from the TeamCity user
interface
1062
Meta-runner
Setup
Kotlin
compiler
fetching
step
Basically this step is limited to defining the Step Name and the version of Kotlin you need. Tags can be used.
The runner will set the value for the property system.path.macro.KOTLIN.BUNDLED to the correct one based on the path
settings from the IntelliJ IDEA project. However, this value needs to be defined in TeamCity (and can be set to any value).
Therefore, you need to define it as a system variable.
Setup
Kotlin
compilation
step
The final step is to define the actual compilation of the project, which uses the standard IntelliJ IDEA Runner Type.
1063
IntelliJ IDEA Runner
With that, our project should now build and produce the corresponding artifacts.
Other
CI
servers
If using a continuous integration tool different to TeamCity, as long as it supports any of the build tools, or calling
command line tools, compiling Kotlin and automating things as part of a CI process should be possible.
Document
Kotlin
code:
KDoc
and
Dokka
The language used to document Kotlin code (the equivalent of Java's JavaDoc) is called KDoc. In its essence, KDoc
combines JavaDoc's syntax for block tags (extended to support Kotlin's specific constructs) and Markdown for inline
markup.
Generate
the
documentation
Kotlin's documentation generation tool is called Dokka. See the Dokka README for usage instructions.
Dokka has plugins for Gradle, Maven, and Ant, so you can integrate documentation generation into your build process.
KDoc
syntax
Just like with JavaDoc, KDoc comments start with /** and end with */. Every line of the comment may begin with an
asterisk, which is not considered part of the contents of the comment.
By convention, the first paragraph of the documentation text (the block of text until the first blank line) is the summary
description of the element, and the following text is the detailed description.
1064
Every block tag begins on a new line and starts with the @ character.
/**
* A group of *members*.
*
* This class has no useful logic; it's just a documentation example.
*
* @param T the type of a member in this group.
* @property name the name of this group.
* @constructor Creates an empty group.
*/
class Group<T>(val name: String) {
/**
* Adds a [member] to this group.
* @return the new size of the group.
*/
fun add(member: T): Int { ... }
}
Block
tags
KDoc currently supports the following block tags:
@param
name
Documents a value parameter of a function or a type parameter of a class, property or function. To better separate the
parameter name from the description, if you prefer, you can enclose the name of the parameter in brackets. The following
two syntaxes are therefore equivalent:
@return
Documents the return value of a function.
@constructor
Documents the primary constructor of a class.
@receiver
Documents the receiver of an extension function.
@property
name
Documents the property of a class which has the specified name. This tag can be used for documenting properties
declared in the primary constructor, where putting a doc comment directly before the property definition would be
1065
awkward.
@throws
class,
@exception
class
Documents an exception which can be thrown by a method. Since Kotlin does not have checked exceptions, there is also
no expectation that all possible exceptions are documented, but you can still use this tag when it provides useful
information for users of the class.
@sample
identifier
Embeds the body of the function with the specified qualified name into the documentation for the current element, in
order to show an example of how the element could be used.
@see
identifier
Adds a link to the specified class or method to the See also block of the documentation.
@author
Specifies the author of the element being documented.
@since
Specifies the version of the software in which the element being documented was introduced.
@suppress
Excludes the element from the generated documentation. Can be used for elements which are not part of the official API
of a module but still have to be visible externally.
KDoc does not support the @deprecated tag. Instead, please use the @Deprecated annotation.
Inline
markup
For inline markup, KDoc uses the regular Markdown syntax, extended to support a shorthand syntax for linking to other
elements in the code.
Links
to
elements
To link to another element (class, method, property, or parameter), simply put its name in square brackets:
1066
Use [this method][foo] for this purpose.
You can also use qualified names in the links. Note that, unlike JavaDoc, qualified names always use the dot character to
separate the components, even before a method name:
Note that KDoc does not have any syntax for resolving overloaded members in links. Since the Kotlin documentation
generation tool puts the documentation for all overloads of a function on the same page, identifying a specific overloaded
function is not required for the link to work.
Module
and
package
documentation
Documentation for a module as a whole, as well as packages in that module, is provided as a separate Markdown file,
and the paths to that file is passed to Dokka using the -include command line parameter or the corresponding parameters
in Ant, Maven and Gradle plugins.
Inside the file, the documentation for the module as a whole and for individual packages is introduced by the
corresponding first-level headings. The text of the heading must be Module <module name> for the module, and Package
<package qualified name> for a package.
# Module kotlin-demo
# Package org.jetbrains.kotlin.demo
## Level 2 heading
# Package org.jetbrains.kotlin.demo2
Kotlin
and
OSGi
To enable Kotlin OSGi support in your Kotlin project, include kotlin-osgi-bundle instead of the regular Kotlin libraries. It is
recommended to remove kotlin-runtime, kotlin-stdlib and kotlin-reflect dependencies as kotlin-osgi-bundle already
contains all of them. You also should pay attention in case when external Kotlin libraries are included. Most regular Kotlin
dependencies are not OSGi-ready, so you shouldn't use them and should remove them from your project.
1067
Maven
To include the Kotlin OSGi bundle to a Maven project:
<dependencies>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-osgi-bundle</artifactId>
<version>${kotlin.version}</version>
</dependency>
</dependencies>
To exclude the standard library from external libraries (notice that "star exclusion" works in Maven 3 only):
<dependency>
<groupId>some.group.id</groupId>
<artifactId>some.library</artifactId>
<version>some.library.version</version>
<exclusions>
<exclusion>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>*</artifactId>
</exclusion>
</exclusions>
</dependency>
Gradle
To include kotlin-osgi-bundle to a Gradle project:
compile "org.jetbrains.kotlin:kotlin-osgi-bundle:$kotlinVersion"
To exclude default Kotlin libraries that comes as transitive dependencies you can use the following approach:
dependencies {
compile (
[group: 'some.group.id', name: 'some.library', version: 'someversion'],
.....) {
exclude group: 'org.jetbrains.kotlin'
}
FAQ
Why
not
just
add
required
manifest
options
to
all
Kotlin
libraries
Even though it is the most preferred way to provide OSGi support, unfortunately it couldn't be done for now due to so
1068
called "package split" issue that couldn't be easily eliminated and such a big change is not planned for now. There is
Require-Bundle feature but it is not the best option too and not recommended to use. So it was decided to make a
separate artifact for OSGi.
Learning
materials
overview
You can use the following materials and resources for learning Kotlin:
Idioms – learn how to write idiomatic Kotlin code for popular cases.
Java to Kotlin migration guide: Strings – learn how to perform typical tasks with strings in Java and Kotlin.
Kotlin Koans – complete exercises to learn the Kotlin syntax. Each exercise is created as a failing unit test and your
job is to make it pass.
Kotlin by example – review a set of small and simple annotated examples for the Kotlin syntax.
Kotlin Basics track – learn all the Kotlin essentials while creating working applications step by step on JetBrains
Academy.
Kotlin books – find books we’ve reviewed and recommend for learning Kotlin.
Kotlin hands-on tutorials – complete long-form tutorials to fully grasp a technology. These tutorials guide you
through a self-contained project related to a specific topic.
Kotlin for Java Developers – course for developers with experience in Java. It shows the similarities between the two
languages and focuses on what’s going to be different.
Kotlin documentation in the PDF format – read the whole documentation offline.
Kotlin
Koans
Kotlin Koans are a series of exercises to get you familiar with the Kotlin Syntax. Each exercise is created as a failing unit
test and your job is to make it pass. You can work with Kotlin Koans in one of following two ways:
2. You can perform the tasks right inside IntelliJ IDEA or Android Studio by installing the EduTools plugin and choosing
Kotlin Koans course.
Whatever way you choose to solve koans, you can see the solution for each task: in the online version click on "Show
answer", inside EduTools plugin choose "Peek solution". We recommend checking the solution after you implement the
task to compare your solution with the proposed one. Make sure you don't cheat!
Kotlin
books
1069
More and more authors write books for learning Kotlin in different languages. We are very thankful to all of them and
appreciate all their efforts in helping us increase a number of professional Kotlin developers.
Here are just a few books we've reviewed and recommend you for learning Kotlin. You can find more books on our
community website.
Head First Kotlin is a complete introduction to coding in Kotlin. This hands-on book helps you
Head First Kotlin
learn the Kotlin language with a unique method that goes beyond syntax and how-to
manuals and teaches you how to think like a great Kotlin developer.
If you want to really understand Kotlin, this is the book for you.
1070
Kotlin in Action teaches you to use the Kotlin language for production-quality applications.
Kotlin in Action Written for experienced Java developers, this example-rich book goes further than most
language books, covering interesting topics like building DSLs with natural language syntax.
The book is written by Dmitry Jemerov and Svetlana Isakova, developers on the Kotlin
team.
Chapter 6, covering the Kotlin type system, and chapter 11, covering DSLs, are available as
a free preview on the publisher web site.
1071
Kotlin Programming: The
Big Nerd Ranch Guide
In this book you will learn to work effectively with the Kotlin language through carefully
considered examples designed to teach you Kotlin’s elegant style and features.
Starting from first principles, you will work your way to advanced usage of Kotlin,
empowering you to create programs that are more reliable with less code.
1072
Programming Kotlin is written by Venkat Subramaniam.
Programming Kotlin
Programmers don’t just use Kotlin, they love it. Even Google has adopted it as a first-
class language for Android development.
With Kotlin, you can intermix imperative, functional, and object-oriented styles of
programming and benefit from the approach that’s most suitable for the problem at
hand.
Learn to use the many features of this highly concise, fluent, elegant, and expressive
statically typed language with easy-to-understand examples.
Learn to write maintainable, high-performing JVM and Android applications, create DSLs,
program asynchronously, and much more.
1073
The Joy of Kotlin teaches you the right way to code in Kotlin.
The Joy of Kotlin
In this insight-rich book, you'll master the Kotlin language while exploring coding techniques
that will make you a better developer no matter what language you use. Kotlin natively
supports a functional style of programming, so seasoned author Pierre-Yves Saumont
begins by reviewing the FP principles of immutability, referential transparency, and the
separation between functions and effects.
Then, you'll move deeper into using Kotlin in the real world, as you learn to handle errors
and data properly, encapsulate shared state mutations, and work with laziness.
This book will change the way you code — and give you back some of the joy you had
when you first started.
Learning
Kotlin
with
EduTools
plugin
With the EduTools plugin, available both in Android Studio and IntelliJ IDEA, you can learn Kotlin through code practicing
tasks.
Take a look at the Learner Start Guide, which will get you started with the Kotlin Koans course inside IntelliJ IDEA. Solve
interactive coding challenges and get instant feedback right inside the IDE.
If you want to use the EduTools plugin for teaching, read Teaching Kotlin with EduTools plugin.
Teaching
Kotlin
with
EduTools
plugin
With the EduTools plugin, available both in Android Studio and IntelliJ IDEA, you can teach Kotlin through code practicing
tasks. Take a look at the Educator Start Guide to learn how to create a simple Kotlin course that includes a set of
programming tasks and integrated tests.
If you want to use the EduTools plugin to learn Kotlin, read Learning Kotlin with EduTools plugin.
FAQ
1074
What
is
Kotlin?
Kotlin is an open-source statically typed programming language that targets the JVM, Android, JavaScript and Native.
It’s developed by JetBrains. The project started in 2010 and was open source from very early on. The first official 1.0
release was in February 2016.
What
is
the
current
version
of
Kotlin?
The currently released version is 1.5.31, published on September 20, 2021.
Is
Kotlin
free?
Yes. Kotlin is free, has been free and will remain free. It is developed under the Apache 2.0 license and the source code is
available on GitHub.
Is
Kotlin
an
object-oriented
language
or
a
functional
one?
Kotlin has both object-oriented and functional constructs. You can use it in both OO and FP styles, or mix elements of the
two. With first-class support for features such as higher-order functions, function types and lambdas, Kotlin is a great
choice if you’re doing or exploring functional programming.
What
advantages
does
Kotlin
give
me
over
the
Java
programming
language?
Kotlin is more concise. Rough estimates indicate approximately a 40% cut in the number of lines of code. It’s also
more type-safe, e.g. support for non-nullable types makes applications less prone to NPE’s. Other features including
smart casting, higher-order functions, extension functions and lambdas with receivers provide the ability to write
expressive code as well as facilitating creation of DSL.
Is
Kotlin
compatible
with
the
Java
programming
language?
Yes. Kotlin is 100% interoperable with the Java programming language and major emphasis has been placed on making
sure that your existing codebase can interact properly with Kotlin. You can easily call Kotlin code from Java and Java
code from Kotlin. This makes adoption much easier and lower-risk. There’s also an automated Java-to-Kotlin
converter built into the IDE that simplifies migration of existing code.
What
can
I
use
Kotlin
for?
Kotlin can be used for any kind of development, be it server-side, client-side web and Android. With Kotlin/Native
1075
currently in the works, support for other platforms such as embedded systems, macOS and iOS is coming. People are
using Kotlin for mobile and server-side applications, client-side with JavaScript or JavaFX, and data science, just to name
a few possibilities.
Can
I
use
Kotlin
for
Android
development?
Yes. Kotlin is supported as a first-class language on Android. There are hundreds of applications already using Kotlin for
Android, such as Basecamp, Pinterest and more. For more information check out the resource on Android development.
Can
I
use
Kotlin
for
server-side
development?
Yes. Kotlin is 100% compatible with the JVM and as such you can use any existing frameworks such as Spring Boot,
vert.x or JSF. In addition there are specific frameworks written in Kotlin such as Ktor. For more information check out the
resource on server-side development.
Can
I
use
Kotlin
for
web
development?
Yes. In addition to using for backend web, you can also use Kotlin/JS for client-side web. Kotlin can use definitions from
DefinitelyTyped to get static typing for common JavaScript libraries, and it is compatible with existing module systems
such as AMD and CommonJS. For more information check out the resource on client-side development.
Can
I
use
Kotlin
for
desktop
development?
Yes. You can use any Java UI framework such as JavaFx, Swing or other. In addition there are Kotlin specific frameworks
such as TornadoFX.
Can
I
use
Kotlin
for
native
development?
Yes. Kotlin/Native is available as a part of Kotlin project. It compiles Kotlin to native code that can run without a VM. It is
still in beta, but you can already try it on popular desktop and mobile platforms and even some IoT devices. For more
information, check out the Kotlin/Native documentation.
What
IDEs
support
Kotlin?
Kotlin is supported by all major Java IDEs including IntelliJ IDEA, Android Studio, and Eclipse. In addition, a command
line compiler is available and provides straightforward support for compiling and running applications.
What
build
tools
support
Kotlin?
1076
On the JVM side, the main build tools include Gradle, Maven, Ant, and Kobalt. There are also some build tools available
that target client-side JavaScript.
What
does
Kotlin
compile
down
to?
When targeting the JVM, Kotlin produces Java compatible bytecode.
When targeting JavaScript, Kotlin transpiles to ES5.1 and generates code which is compatible with module systems
including AMD and CommonJS.
When targeting native, Kotlin will produce platform-specific code (via LLVM).
Which
versions
of
JVM
does
Kotlin
target?
Kotlin lets you choose the version of JVM for execution. By default, the Kotlin/JVM compiler produces Java 8 compatible
bytecode. If you want to make use of optimizations available in newer versions of Java, you can explicitly specify the
target Java version from 9 to 16. Note that in this case the resulting bytecode might not run on lower versions.
Is
Kotlin
hard?
Kotlin is inspired by existing languages such as Java, C#, JavaScript, Scala and Groovy. We've tried to ensure that Kotlin
is easy to learn, so that people can easily jump on board, reading and writing Kotlin in a matter of days. Learning idiomatic
Kotlin and using some more of its advanced features can take a little longer, but overall it is not a complicated language.
What
companies
are
using
Kotlin?
There are too many companies using Kotlin to list, but some more visible companies that have publicly declared usage of
Kotlin, be this via blog posts, GitHub repositories or talks include Square, Pinterest, Basecamp, and Corda.
Who
develops
Kotlin?
Kotlin is primarily developed by a team of engineers at JetBrains (current team size is 100+). The lead language designer
is Roman Elizarov. In addition to the core team, there are also over 250 external contributors on GitHub.
Where
can
I
learn
more
about
Kotlin?
The best place to start is this website. From there you can download the compiler, try it online as well as get access to
resources.
1077
Are
there
any
books
on
Kotlin?
There are a number of books available for Kotlin. Some of them we have reviewed and can recommend to start with. They
are listed on the Books page. For more books, see the community-maintained list at kotlin.link.
Are
any
online
courses
available
for
Kotlin?
You can learn all the Kotlin essentials while creating working applications with the Kotlin Basics track on JetBrains
Academy.
You can also check out the other tutorials and content on our YouTube channel.
Does
Kotlin
have
a
community?
Yes. Kotlin has a very vibrant community. Kotlin developers hang out on the Kotlin forums, StackOverflow and more
actively on the Kotlin Slack (with close to 30000 members as of April 2020).
Are
there
Kotlin
events?
Yes. There are many User Groups and Meetups now focused exclusively around Kotlin. You can find a list on the web
site. In addition, there are community-organized Kotlin Nights events around the world.
Is
there
a
Kotlin
conference?
Yes. The official annual KotlinConf is hosted by JetBrains. It took place in San-Francisco in 2017, Amsterdam in 2018,
and Copenhagen in 2019. Kotlin is also being covered in different conferences worldwide. You can find a list of upcoming
talks on the web site.
Is
Kotlin
on
social
media?
Yes. The most active Kotlin account is on Twitter.
Any
other
online
Kotlin
resources?
1078
The web site has a bunch of online resources, including Kotlin Digests by community members, a newsletter, a podcast
and more.
Where
can
I
get
an
HD
Kotlin
logo?
Logos can be downloaded here. When using the logos, please follow simple rules in the guidelines.pdf inside the archive
and Kotlin brand usage guidelines.
Participate
in
the
Kotlin
Early
Access
Preview
You can participate in the Kotlin Early Access Preview (EAP) to try out the latest Kotlin features before they are released.
We ship a few Milestone (M) builds before every feature (1.x) and incremental (1.x.y) release.
We’ll be very thankful if you find and report bugs to our issue tracker YouTrack. It is very likely that we’ll be able to
fix them before the final release, which means you won’t need to wait until the next Kotlin release for your issues to
be addressed.
By participating in the Early Access Preview and reporting bugs, you contribute to Kotlin and help us make it better for
everyone in the growing Kotlin community. We appreciate your help a lot!
If you have any questions and want to participate in discussions, you are welcome to join the #eap channel in Kotlin Slack.
In this channel, you can also get notifications about new EAP builds.
By participating in the EAP, you expressly acknowledge that the EAP version may not be reliable, may not work
as intended, and may contain errors.
Please note that we don’t provide any guarantees of compatibility between EAP and final versions of the
same release.
If you have already installed the EAP version and want to work on projects that were created previously, check our
instructions on how to configure your build to support this version.
Build
details
1079
Build info Build highlights Recommended kotlinx library
versions
1.6.0-M1 Language: support for conversions from regular functional types kotlinx.serialization version: 1.3.0-
Released: to suspending ones, support for repeatable annotations with the RC
September RUNTIME retention
kotlinx.coroutines version: 1.5.2
24, 2021
Kotlin/JVM: bytecode optimizations for delegated properties
Release on kotlinx.atomicfu version: 0.16.3
GitHub
Kotlin/Native: a preview of the new memory manager, support for
ktor version: 1.6.3
Xcode 13, updated LLVM to 11.1.0, compiler caches enabled by
default for linuxX64 and iosArm64, cross-compilation for MinGW
kotlinx.html version: 0.7.2
targets
kotlinx-nodejs version: 0.0.7
Kotlin/JS: ability to disable downloading Node.js and Yarn
The versions of libraries from kotlin-
Gradle: removed kotlin.useFallbackCompilerSearch build option
wrappers (such as kotlin-react) can
be found in the corresponding
stdlib: top-level readln() and readlnOrNull() on JVM, stable
repository.
typeOf()
Install
the
EAP
Plugin
for
IntelliJ
IDEA
or
Android
Studio
You can follow these instructions to install the preview version of the Kotlin Plugin for IntelliJ IDEA or Android Studio.
1080
Select Kotlin Plugin Updates
2. In the Update channel list, select the Early Access Preview X channel, where X is the latest version of Kotlin.
1081
Select the EAP update channel
4. Click Install.
If you want to work on existing projects that were created before installing the EAP version, you need to configure your
build for EAP.
If
you
run
into
any
problems
Report an issue to our issue tracker, YouTrack.
Roll back to the latest stable version: in Tools | Kotlin | Configure Kotlin Plugin Updates, select the Stable update
channel and click Install.
Configure
your
build
for
EAP
1082
If you create new projects using the EAP version of Kotlin, you don’t need to perform any additional steps. The Kotlin
Plugin will do everything for you!
You only need to configure your build manually for existing projects — projects that were created before installing the
EAP version.
To configure your build to use the EAP version of Kotlin, you need to:
Specify the EAP version of Kotlin. Available EAP versions are listed here.
Change the versions of dependencies to EAP ones. The EAP version of Kotlin may not work with the libraries of the
previously released version.
The following procedures describe how to configure your build in Gradle and Maven:
Configure in Gradle
Configure in Maven
Configure
in
Gradle
This section describes how you can:
Adjust
the
Kotlin
version
In the plugins block within build.gradle(.kts), change the KOTLIN-EAP-VERSION to the actual EAP version, such as 1.6.0-
M1. Available EAP versions are listed here.
Alternatively, you can specify the EAP version in the pluginManagement block in settings.gradle(.kts) – see Gradle
documentation for details.
Kotlin
plugins {
java
kotlin("multiplatform") version "KOTLIN-EAP-VERSION"
}
repositories {
mavenCentral()
}
Groovy
1083
plugins {
id 'java'
id 'org.jetbrains.kotlin.multiplatform' version 'KOTLIN-EAP-VERSION'
}
repositories {
mavenCentral()
}
Adjust
versions
in
dependencies
If you use kotlinx libraries in your project, your versions of the libraries may not be compatible with the EAP version of
Kotlin.
To resolve this issue, you need to specify the version of a compatible library in dependencies. For a list of compatible
libraries, see EAP build details.
In most cases we create libraries only for the first EAP version of a specific release and these libraries work with
the subsequent EAP versions for this release.
If there are incompatible changes in next EAP versions, we release a new version of the library.
Here is an example.
For the kotlinx.coroutines library, add the version number – 1.5.0-RC – that is compatible with 1.6.0-M1.
Kotlin
dependencies {
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.5.0-RC")
}
Groovy
dependencies {
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.5.0-RC"
}
Configure
in
Maven
In the sample Maven project definition, replace KOTLIN-EAP-VERSION with the actual version, such as 1.6.0-M1.
Available EAP versions are listed here.
<project ...>
1084
<properties>
<kotlin.version>KOTLIN-EAP-VERSION</kotlin.version>
</properties>
<repositories>
<repository>
<id>mavenCentral</id>
<url>https://repo1.maven.org/maven2/</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>mavenCentral</id>
<url>https://repo1.maven.org/maven2/</url>
</pluginRepository>
</pluginRepositories>
<dependencies>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib</artifactId>
<version>${kotlin.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-plugin</artifactId>
<version>${kotlin.version}</version>
...
</plugin>
</plugins>
</build>
</project>
Contribution
Kotlin is an open-source project under the Apache 2.0 License. The source code, tooling, documentation, and even this
web site are maintained on GitHub. While Kotlin is mostly developed by JetBrains, there are hundreds of external
contributors to the Kotlin project and we are always on the lookout for more people to help us.
Participate
in
Early
Access
Preview
You can help us improve Kotlin by participating in Kotlin Early Access Preview (EAP) and providing us with your valuable
feedback.
For every release, Kotlin ships a few preview builds where you can try out the latest features before they go to production.
You can report any bugs you find to our issue tracker YouTrack and we will try to fix them before a final release. This way,
you can get bug fixes earlier than the standard Kotlin release cycle.
1085
Contribute
to
the
compiler,
standard
library,
and
tooling
If you want to contribute to the Kotlin compiler, standard library, or tooling, go to GitHub, check out the latest Kotlin
version, and follow the instructions on how to contribute.
You can help us by completing open tasks. Please keep an open line of communication with us because we may have
questions and comments on your changes. Otherwise, we won't be able to incorporate your contributions.
Contribute
to
other
libraries
and
create
your
own
Besides the standard library that provides core capabilities, Kotlin has a number of additional (kotlinx) libraries that extend
its functionality. Each kotlinx library is developed in a separate repository, has its own versioning and release cycle.
If you want to contribute to a kotlinx library, follow the contribution process described for each library, such as
kotlinx.coroutines, kotlinx.serialization, and ktor.
If you have a library that could be useful to other Kotlin developers, let us know via feedback@kotlinlang.org.
Contribute
to
the
documentation
If you've found an issue in the Kotlin documentation, feel free to check out the documentation source code on GitHub and
send us a pull request. Follow these guidelines on style and formatting.
Please keep an open line of communication with us because we may have questions and comments on your changes.
Otherwise, we won't be able to incorporate your contributions.
Create
tutorials
or
videos
If you've created tutorials or videos for Kotlin, please share them with us via feedback@kotlinlang.org.
Translate
documentation
to
other
languages
You are welcome to translate the Kotlin documentation into your own language and publish the translation on your
website. However, we won't be able to host your translation in the main repository and publish it on kotlinlang.org.
This site is the official documentation for the language, and we ensure that all the information here is correct and up to
date. Unfortunately, we won't be able to review documentation in other languages.
Hold
events
and
presentations
If you've given or just plan to give presentations or hold events on Kotlin, please fill out the form. We'll feature them on the
event list.
1086
Kotlin
Evolution
Principles
of
Pragmatic
Evolution
Kotlin is designed to be a pragmatic tool for programmers. When it comes to language evolution, its pragmatic nature is
captured by the following principles:
As this is key to understanding how Kotlin is moving forward, let's expand on these principles.
Keeping the Language Modern. We acknowledge that systems accumulate legacy over time. What had once been
cutting-edge technology can be hopelessly outdated today. We have to evolve the language to keep it relevant to the
needs of the users and up-to-date with their expectations. This includes not only adding new features, but also phasing
out old ones that are no longer recommended for production use and have altogether become legacy.
Comfortable Updates. Incompatible changes, such as removing things from a language, may lead to painful migration
from one version to the next if carried out without proper care. We will always announce such changes well in advance,
mark things as deprecated and provide automated migration tools before the change happens. By the time the language
is changed we want most of the code in the world to be already updated and thus have no issues migrating to the new
version.
Feedback Loop. Going through deprecation cycles requires significant effort, so we want to minimize the number of
incompatible changes we'll be making in the future. Apart from using our best judgement, we believe that trying things out
in real life is the best way to validate a design. Before casting things in stone we want them battle-tested. This is why we
use every opportunity to make early versions of our designs available in production versions of the language, but in one of
the pre-stable statuses: Experimental, Alpha, or Beta. Such features are not stable, they can be changed at any time, and
the users that opt into using them do so explicitly to indicate that they are ready to deal with the future migration issues.
These users provide invaluable feedback that we gather to iterate on the design and make it rock-solid.
Incompatible
changes
1087
If, upon updating from one version to another, some code that used to work doesn't work any more, it is an incompatible
change in the language (sometimes referred to as "breaking change"). There can be debates as to what "doesn't work
any more" means precisely in some cases, but it definitely includes the following:
Code that compiled and ran fine is now rejected with an error (at compile or link time). This includes removing
language constructs and adding new restrictions.
The less obvious cases that belong to the "grey area" include handling corner cases differently, throwing an exception of
a different type than before, changing behavior observable only through reflection, changes in undocumented/undefined
behavior, renaming binary artifacts, etc. Sometimes such changes are very important and affect migration experience
dramatically, sometimes they are insignificant.
The principles of Keeping the Language Modern and Comfortable Updates suggest that incompatible changes are
sometimes necessary, but they should be introduced carefully. Our goal is to make the users aware of upcoming changes
well in advance to let them migrate their code comfortably.
Ideally, every incompatible change should be announced through a compile-time warning reported in the problematic
code (usually referred to as a deprecation warning) and accompanied with automated migration aids. So, the ideal
migration workflow goes as follows:
In practice some changes can't be accurately detected at compile time, so no warnings can be reported, but at least the
users will be notified through Release notes of version A that a change is coming in version B.
Dealing
with
compiler
bugs
Compilers are complicated software and despite the best effort of their developers they have bugs. The bugs that cause
the compiler itself to fail or report spurious errors or generate obviously failing code, though annoying and often
embarrassing, are easy to fix, because the fixes do not constitute incompatible changes. Other bugs may cause the
compiler to generate incorrect code that does not fail: e.g. by missing some errors in the source or simply generating
wrong instructions. Fixes of such bugs are technically incompatible changes (some code used to compile fine, but now it
won't any more), but we are inclined to fixing them as soon as possible to prevent the bad code patterns from spreading
across user code. In our opinion, this serves the principle of Comfortable Updates, because fewer users have a chance of
1088
encountering the issue. Of course, this applies only to bugs that are found soon after appearing in a released version.
Decision
making
JetBrains, the original creator of Kotlin, is driving its progress with the help of the community and in accord with the Kotlin
Foundation.
All changes to the Kotlin Programming Language are overseen by the Lead Language Designer (currently Roman
Elizarov). The Lead Designer has the final say in all matters related to language evolution. Additionally, incompatible
changes to fully stable components have to be approved to by the Language Committee designated under the Kotlin
Foundation (currently comprised of Jeffrey van Gogh, William R. Cook and Roman Elizarov).
The Language Committee makes final decisions on what incompatible changes will be made and what exact measures
should be taken to make user updates comfortable. In doing so, it relies on a set of guidelines available here.
Feature
releases
and
incremental
releases
Stable releases with versions 1.2, 1.3, etc. are usually considered to be feature releases bringing major changes in the
language. Normally, we publish incremental releases, numbered 1.2.20, 1.2.30, etc, in between feature releases.
Incremental releases bring updates in the tooling (often including features), performance improvements and bug fixes. We
try to keep such versions compatible with each other, so changes to the compiler are mostly optimizations and warning
additions/removals. Pre-stable features may, of course, be added, removed or changed at any time.
Feature releases often add new features and may remove or change previously deprecated ones. Feature graduation from
pre-stable to stable also happens in feature releases.
EAP
builds
Before releasing stable versions, we usually publish a number of preview builds dubbed EAP (for "Early Access Preview")
that let us iterate faster and gather feedback from the community. EAPs of feature releases usually produce binaries that
will be later rejected by the stable compiler to make sure that possible bugs in the binary format survive no longer than the
preview period. Final Release Candidates normally do not bear this limitation.
Pre-stable
features
According to the Feedback Loop principle described above, we iterate on our designs in the open and release versions of
the language where some features have one of the pre-stable statuses and are supposed to change. Such features can
be added, changed or removed at any point and without warning. We do our best to ensure that pre-stable features can't
be used accidentally by an unsuspecting user. Such features usually require some sort of an explicit opt-in either in the
code or in the project configuration.
Pre-stable features usually graduate to the stable status after some iterations.
1089
Status
of
different
components
To check the stability status of different components of Kotlin (Kotlin/JVM, JS, Native, various libraries, etc), please
consult this link.
Libraries
A language is nothing without its ecosystem, so we pay extra attention to enabling smooth library evolution.
Ideally, a new version of a library can be used as a "drop-in replacement" for an older version. This means that upgrading
a binary dependency should not break anything, even if the application is not recompiled (this is possible under dynamic
linking).
On the one hand, to achieve this, the compiler has to provide certain ABI stability guarantees under the constraints of
separate compilation. This is why every change in the language is examined from the point of view of binary compatibility.
On the other hand, a lot depends on the library authors being careful about which changes are safe to make. Thus it's
very important that library authors understand how source changes affect compatibility and follow certain best practices
to keep both APIs and ABIs of their libraries stable. Here are some assumptions that we make when considering language
changes from the library evolution standpoint:
Library code should always specify return types of public/protected functions and properties explicitly thus never
relying on type inference for public API. Subtle changes in type inference may cause return types to change
inadvertently, leading to binary compatibility issues.
Overloaded functions and properties provided by the same library should do essentially the same thing. Changes in
type inference may result in more precise static types to be known at call sites causing changes in overload resolution.
Library authors can use the @Deprecated and @RequiresOptIn annotations to control the evolution of their API surface.
Note that @Deprecated(level=HIDDEN) can be used to preserve binary compatibility even for declarations removed from
the API.
Also, by convention, packages named "internal" are not considered public API. All API residing in packages named
"experimental" is considered pre-stable and can change at any moment.
We evolve the Kotlin Standard Library (kotlin-stdlib) for stable platforms according to the principles stated above.
Changes to the contracts for its API undergo the same procedures as changes in the language itself.
Compiler
keys
Command line keys accepted by the compiler are also a kind of public API, and they are subject to the same
considerations. Supported flags (those that don't have the "-X" or "-XX" prefix) can be added only in feature releases and
should be properly deprecated before removing them. The "-X" and "-XX" flags are experimental and can be added and
removed at any time.
Compatibility
tools
1090
As legacy features get removed and bugs fixed, the source language changes, and old code that has not been properly
migrated may not compile any more. The normal deprecation cycle allows a comfortable period of time for migration, and
even when it's over and the change ships in a stable version, there's still a way to compile unmigrated code.
Compatibility
flags
We provide the -language-version and -api-version flags that make a new version emulate the behavior of an old one, for
compatibility purposes. Normally, at least one previous version is supported. This effectively leaves a time span of two full
feature release cycles for migration (which usually amounts to about two years). Using an older kotlin-stdlib or kotlin-
reflect with a newer compiler without specifying compatibility flags is not recommended, and the compiler will report a
warning when this happens.
Actively maintained code bases can benefit from getting bug fixes ASAP, without waiting for a full deprecation cycle to
complete. Currently such project can enable the -progressive flag and get such fixes enabled even in incremental
releases.
All flags are available on the command line as well as Gradle and Maven.
Evolving
the
binary
format
Unlike sources that can be fixed by hand in the worst case, binaries are a lot harder to migrate, and this makes
backwards compatibility very important in the case of binaries. Incompatible changes to binaries can make updates very
uncomfortable and thus should be introduced with even more care than those in the source language syntax.
For fully stable versions of the compiler the default binary compatibility protocol is the following:
All binaries are backwards compatible, i.e. a newer compiler can read older binaries (e.g. 1.3 understands 1.0 through
1.2),
Older compilers reject binaries that rely on new features (e.g. a 1.0 compiler rejects binaries that use coroutines).
Preferably (but we can't guarantee it), the binary format is mostly forwards compatible with the next feature release,
but not later ones (in the cases when new features are not used, e.g. 1.3 can understand most binaries from 1.4, but
not 1.5).
This protocol is designed for comfortable updates as no project can be blocked from updating its dependencies even if
it's using a slightly outdated compiler.
Please note that not all target platforms have reached this level of stability (but Kotlin/JVM has).
Stability
of
Kotlin
components
The Kotlin language and toolset are divided into many components such as the compilers for the JVM, JS and Native
targets, the Standard Library, various accompanying tools and so on. Many of these components were officially released
as Stable which means that they are evolved in the backward-compatible way following the principles of Comfortable
Updates and Keeping the Language Modern. Among such stable components are, for example, the Kotlin compiler for
1091
the JVM, the Standard Library, and Coroutines.
Following the Feedback Loop principle we release many things early for the community to try out, so a number of
components are not yet released as Stable. Some of them are very early stage, some are more mature. We mark them as
Experimental, Alpha or Beta depending on how quickly each component is evolving and how much risk the users are
taking when adopting it.
Stability
levels
explained
Here's a quick guide to these stability levels and their meaning:
We are just trying out an idea and want some users to play with it and give feedback. If it doesn't work out, we may
drop it any minute.
We decided to productize this idea, but it hasn't reached the final shape yet.
Beta means "you can use it, we'll do our best to minimize migration issues for you":
Still, it's not 100% finished, so changes are possible (including ones based on your own feedback).
Watch for deprecation warnings in advance for the best update experience.
It’s done. We will be evolving it according to our strict backward compatibility rules.
Please note that stability levels do not say anything about how soon a component will be released as Stable. Similarly,
they do not indicate how much a component will be changed before release. They only say how fast a component is
changing and how much risk of update issues users are running.
Stability
of
subcomponents
A stable component may have an experimental subcomponent, for example:
We make sure to document precisely which subcomponents are not stable. We also do our best to warn users where
1092
possible and ask to opt in explicitly to avoid accidental usages of features that have not been released as stable.
Current
stability
of
Kotlin
components
KMM plugin for Android Studio Experimental 0.1 Versioned separately from the language
1093
Component Status Status since version Comment
Serialization Core Library Stable 1.0.0 Versioned separately from the language
Stability
of
Kotlin
components
(pre
1.4)
There can be different modes of stability depending of how quickly a component is evolving:
Moving fast (MF): no compatibility should be expected between even incremental releases, any functionality can be
added, removed or changed without warning.
Additions in Incremental Releases (AIR): things can be added in an incremental release, removals and changes of
behavior should be avoided and announced in a previous incremental release if necessary.
Stable Incremental Releases (SIR): incremental releases are fully compatible, only optimizations and bug fixes happen.
Any changes can be made in a feature release.
Fully Stable (FS): incremental releases are fully compatible, only optimizations and bug fixes happen. Feature releases
are backwards compatible.
Source and binary compatibility may have different modes for the same component, e.g. the source language can reach
full stability before the binary format stabilizes, or vice versa.
The provisions of the Kotlin evolution policy fully apply only to components that have reached Full Stability (FS). From that
point on incompatible changes have to be approved by the Language Committee.
1094
Component Status Entered at version Mode for Sources Mode for Binaries
Kotlin/JVM 1.0 FS FS
Coroutines 1.3 FS FS
Serialization 1.3 MF MF
Compatibility
guide
for
Kotlin
1.5
Keeping the Language Modern* and *Comfortable Updates are among the fundamental principles in Kotlin Language
Design. The former says that constructs which obstruct language evolution should be removed, and the latter says that
this removal should be well-communicated beforehand to make code migration as smooth as possible.
While most of the language changes were already announced through other channels, like update changelogs or compiler
warnings, this document summarizes them all, providing a complete reference for migration from Kotlin 1.4 to Kotlin 1.5.
1095
Basic
terms
In this document we introduce several kinds of compatibility:
source: source-incompatible change stops code that used to compile fine (without errors or warnings) from compiling
anymore
binary: two binary artifacts are said to be binary-compatible if interchanging them doesn't lead to loading or linkage
errors
behavioral: a change is said to be behavioral-incompatible if the same program demonstrates different behavior before
and after applying the change
Remember that those definitions are given only for pure Kotlin. Compatibility of Kotlin code from the other languages
perspective (for example, from Java) is out of the scope of this document.
Language
and
stdlib
Forbid
spread
operator
in
signature-polymorphic
calls
Issue: KT-35226
Short summary: Kotlin 1.5 will outlaw the use of spread operator (*) on signature-polymorphic calls
Deprecation cycle:
Forbid
non-abstract
classes
containing
abstract
members
invisible
from
that
classes
(internal/package-private)
1096
Issue: KT-27825
Short summary: Kotlin 1.5 will outlaw non-abstract classes containing abstract members invisible from that
classes (internal/package-private)
Deprecation cycle:
Forbid
using
array
based
on
non-reified
type
parameters
as
reified
type
arguments
on
JVM
Issue: KT-31227
Short summary: Kotlin 1.5 will outlaw using array based on non-reified type parameters as reified type
arguments on JVM
Deprecation cycle:
Forbid
secondary
enum
class
constructors
which
do
not
delegate
to
the
primary
constructor
1097
Issue: KT-35870
Short summary: Kotlin 1.5 will outlaw secondary enum class constructors which do not delegate to the primary
constructor
Deprecation cycle:
Forbid
exposing
anonymous
types
from
private
inline
functions
Issue: KT-33917
Short summary: Kotlin 1.5 will outlaw exposing anonymous types from private inline functions
Deprecation cycle:
Forbid
passing
non-spread
arrays
after
arguments
with
SAM-conversion
1098
Issue: KT-35224
Short summary: Kotlin 1.5 will outlaw passing non-spread arrays after arguments with SAM-conversion
Deprecation cycle:
Support
special
semantics
for
underscore-named
catch
block
parameters
Issue: KT-31567
Short summary: Kotlin 1.5 will outlaw references to the underscore symbol (_) that is used to omit parameter
name of an exception in the catch block
Deprecation cycle:
Change
implementation
strategy
of
SAM
conversion
from
anonymous
class-based
to
invokedynamic
1099
Issue: KT-44912
Component: Kotlin/JVM
Short summary: Since Kotlin 1.5, implementation strategy of SAM (single abstract method) conversion will be
changed from generating an anonymous class to using the invokedynamic JVM instruction
Deprecation cycle:
1.5: change implementation strategy of SAM conversion, -Xsam-conversions=class can be used to revert
implementation scheme to the one that used before
Performance
issues
with
the
JVM
IR-based
backend
1100
Issue: KT-48233
Component: Kotlin/JVM
Short summary: Kotlin 1.5 uses the IR-based backend for the Kotlin/JVM compiler by default. The old backend
is still used by default for earlier language versions.
You might encounter some performance degradation issues using the new compiler in Kotlin 1.5. We are
working on fixing such cases.
Deprecation cycle:
>= 1.5: by default, the IR-based backend is used. If you need to use the old backend in Kotlin 1.5, add the
following lines to the project's configuration file to temporarily revert to pre-1.5 behavior:
In Gradle:
Kotlin
tasks.withType<org.jetbrains.kotlin.gradle.dsl.KotlinJvmCompile> {
kotlinOptions.useOldBackend = true
}
Groovy
tasks.withType(org.jetbrains.kotlin.gradle.dsl.KotlinJvmCompile) {
kotlinOptions.useOldBackend = true
}
In Maven:
<configuration>
<args>
<arg>-Xuse-old-backend</arg>
</args>
</configuration>
Support for this flag will be removed in one of the future releases.
New
field
sorting
in
the
JVM
IR-based
backend
1101
Issue: KT-46378
Component: Kotlin/JVM
Short summary: Since version 1.5, Kotlin uses the IR-based backend that sorts JVM bytecode differently: it
generates fields declared in the constructor before fields declared in the body, while it's vice versa for the old
backend. The new sorting may change the behavior of programs that use serialization frameworks that depend
on the field order, such as Java serialization.
Deprecation cycle:
< 1.5: by default, the old JVM backend is used. It has fields declared in the body before fields declared in
the constructor.
>= 1.5: by default, the new IR-based backend is used. Fields declared in the constructor are generated
before fields declared in the body. As a workaround, you can temporarily switch to the old backend in Kotlin
1.5. To do that, add the following lines to the project's configuration file:
In Gradle:
Kotlin
tasks.withType<org.jetbrains.kotlin.gradle.dsl.KotlinJvmCompile> {
kotlinOptions.useOldBackend = true
}
Groovy
tasks.withType(org.jetbrains.kotlin.gradle.dsl.KotlinJvmCompile) {
kotlinOptions.useOldBackend = true
}
In Maven:
<configuration>
<args>
<arg>-Xuse-old-backend</arg>
</args>
</configuration>
Support for this flag will be removed in one of the future releases.
Generate
nullability
assertion
for
delegated
properties
with
a
generic
call
in
the
delegate
expression
1102
Issue: KT-44304
Component: Kotlin/JVM
Short summary: Since Kotlin 1.5, the Kotlin compiler will emit nullability assertions for delegated properties with
a generic call in the delegate expression
Deprecation cycle:
1.5: emit nullability assertion for delegated properties (see details in the issue), -Xuse-old-backend or -
language-version 1.4 can be used to temporarily revert to pre-1.5 behavior
Turn
warnings
into
errors
for
calls
with
type
parameters
annotated
by
@OnlyInputTypes
Issue: KT-45861
Short summary: Kotlin 1.5 will outlaw calls like contains, indexOf, and assertEquals with senseless arguments
to improve type safety
Deprecation cycle:
>= 1.5: raise this warning to an error, -XXLanguage:-StrictOnlyInputTypesChecks can be used to temporarily
revert to pre-1.5 behavior
Use
the
correct
order
of
arguments
execution
in
calls
with
named
vararg
1103
Issue: KT-17691
Component: Kotlin/JVM
Short summary: Kotlin 1.5 will change the order of arguments execution in calls with named vararg
Deprecation cycle:
Use
default
value
of
the
parameter
in
operator
functional
calls
Issue: KT-42064
Component: Kotlin/JVM
Short summary: Kotlin 1.5 will use default value of the parameter in operator calls
Deprecation cycle:
>= 1.5: behavior changed, -XXLanguage:-JvmIrEnabledByDefault can be used to temporarily revert to pre-
1.5 behavior
Produce
empty
reversed
progressions
in
for
loops
if
regular
progression
is
also
empty
1104
Issue: KT-42533
Component: Kotlin/JVM
Short summary: Kotlin 1.5 will produce empty reversed progressions in for loops if regular progression is also
empty
Deprecation cycle:
>= 1.5: behavior changed, -XXLanguage:-JvmIrEnabledByDefault can be used to temporarily revert to pre-
1.5 behavior
Straighten
Char-to-code
and
Char-to-digit
conversions
out
Issue: KT-23451
Component: kotlin-stdlib
Short summary: Since Kotlin 1.5, conversions of Char to number types will be deprecated
Deprecation cycle:
Inconsistent
case-insensitive
comparison
of
characters
in
kotlin.text
functions
1105
Issue: KT-45496
Component: kotlin-stdlib
Short summary: Since Kotlin 1.5, Char.equals will be improved in case-insensitive case by first comparing
whether the uppercase variants of characters are equal, then whether the lowercase variants of those
uppercase variants (as opposed to the characters themselves) are equal
Deprecation cycle:
Remove
default
locale-sensitive
case
conversion
API
Issue: KT-43023
Component: kotlin-stdlib
Short summary: Since Kotlin 1.5, default locale-sensitive case conversion functions like String.toUpperCase()
will be deprecated
Deprecation cycle:
1.5: deprecate case conversions functions with the default locale (see details in the issue), and propose
replacement
Gradually
change
the
return
type
of
collection
min
and
max
functions
to
non-nullable
1106
Issue: KT-38854
Short summary: return type of collection min and max functions will be changed to non-nullable in 1.6
Deprecation cycle:
1.4: introduce ...OrNull functions as synonyms and deprecate the affected API (see details in the issue)
>=1.6: reintroduce the affected API but with non-nullable return type
Raise
the
deprecation
level
of
conversions
of
floating-point
types
to
Short
and
Byte
Issue: KT-30360
Short summary: conversions of floating-point types to Short and Byte deprecated in Kotlin 1.4 with WARNING
level will cause errors since Kotlin 1.5.0.
Deprecation cycle:
Tools
Do
not
mix
several
JVM
variants
of
kotlin-test
in
a
single
project
1107
Issue: KT-40225
Component: Gradle
Short summary: several mutually exclusive kotlin-test variants for different testing frameworks could have been
in a project if one of them is brought by a transitive dependency. From 1.5.0, Gradle won't allow having
mutually exclusive kotlin-test variants for different testing frameworks.
Deprecation cycle:
< 1.5: having several mutually exclusive kotlin-test variants for different testing frameworks is allowed
find another variant of the dependency that doesn't bring the kotlin-test variant transitively, so you can
use the testing framework you would like to use.
find another variant of the dependency that brings another kotlin-test variant transitively, which uses the
same testing framework you would like to use.
exclude the testing framework that is brought transitively. The following example is for excluding JUnit 4:
configurations {
testImplementation.get().exclude("org.jetbrains.kotlin", "kotlin-test-junit")
}
After excluding the testing framework, test your application. If it stopped working, rollback excluding
changes, use the same testing framework as the library does, and exclude your testing framework.
Compatibility
guide
for
Kotlin
1.4
Keeping the Language Modern* and *Comfortable Updates are among the fundamental principles in Kotlin Language
Design. The former says that constructs which obstruct language evolution should be removed, and the latter says that
this removal should be well-communicated beforehand to make code migration as smooth as possible.
While most of the language changes were already announced through other channels, like update changelogs or compiler
warnings, this document summarizes them all, providing a complete reference for migration from Kotlin 1.3 to Kotlin 1.4.
Basic
terms
1108
In this document we introduce several kinds of compatibility:
source: source-incompatible change stops code that used to compile fine (without errors or warnings) from compiling
anymore
binary: two binary artifacts are said to be binary-compatible if interchanging them doesn't lead to loading or linkage
errors
behavioral: a change is said to be behavioral-incompatible if the same program demonstrates different behavior before
and after applying the change
Remember that those definitions are given only for pure Kotlin. Compatibility of Kotlin code from the other languages
perspective (for example, from Java) is out of the scope of this document.
Language
and
stdlib
Unexpected
behavior
with
in
infix
operator
and
ConcurrentHashMap
Issue: KT-18053
Short summary: Kotlin 1.4 will outlaw auto operator contains coming from the implementors of java.util.Map
written in Java
Deprecation cycle:
Prohibit
access
to
protected
members
inside
public
inline
members
1109
Issue: KT-21178
Short summary: Kotlin 1.4 will prohibit access to protected members from public inline members.
Deprecation cycle:
Contracts
on
calls
with
implicit
receivers
Issue: KT-28672
Short summary: smart casts from contracts will be available on calls with implicit receivers in 1.4
Deprecation cycle:
Inconsistent
behavior
of
floating-point
number
comparisons
1110
Issues: KT-22723
Short summary: since Kotlin 1.4, Kotlin compiler will use IEEE 754 standard to compare floating-point numbers
Deprecation cycle:
No
smart
cast
on
the
last
expression
in
a
generic
lambda
Issue: KT-15020
Short summary: smart casts for last expressions in lambdas will be correctly applied since 1.4
Deprecation cycle:
>= 1.4: behavior changed, -XXLanguage:-NewInference can be used to temporarily revert to pre-1.4
behavior. Note that this flag will also disable several new language features.
Do
not
depend
on
the
order
of
lambda
arguments
to
coerce
result
to
Unit
1111
Issue: KT-36045
Short summary: since Kotlin 1.4, lambda arguments will be resolved independently without implicit coercion to
Unit
Deprecation cycle:
>= 1.4: behavior changed, -XXLanguage:-NewInference can be used to temporarily revert to pre-1.4
behavior. Note that this flag will also disable several new language features.
Wrong
common
supertype
between
raw
and
integer
literal
type
leads
to
unsound
code
Issue: KT-35681
Short summary: since Kotlin 1.4, common supertype between raw Comparable type and integer literal type will
be more specific
Deprecation cycle:
>= 1.4: behavior changed, -XXLanguage:-NewInference can be used to temporarily revert to pre-1.4
behavior. Note that this flag will also disable several new language features.
Type
safety
problem
because
several
equal
type
variables
are
instantiated
with
a
different
types
1112
Issue: KT-35679
Short summary: since Kotlin 1.4, Kotlin compiler will prohibit instantiating equal type variables with different
types
Deprecation cycle:
>= 1.4: behavior changed, -XXLanguage:-NewInference can be used to temporarily revert to pre-1.4
behavior. Note that this flag will also disable several new language features.
Type
safety
problem
because
of
incorrect
subtyping
for
intersection
types
Issues: KT-22474
Short summary: in Kotlin 1.4, subtyping for intersection types will be refined to work more correctly
Deprecation cycle:
>= 1.4: behavior changed, -XXLanguage:-NewInference can be used to temporarily revert to pre-1.4
behavior. Note that this flag will also disable several new language features.
No
type
mismatch
with
an
empty
when
expression
inside
lambda
1113
Issue: KT-17995
Short summary: since Kotlin 1.4, there will be a type mismatch for empty when expression if it's used as the
last expression in a lambda
Deprecation cycle:
>= 1.4: behavior changed, -XXLanguage:-NewInference can be used to temporarily revert to pre-1.4
behavior. Note that this flag will also disable several new language features.
Return
type
Any
inferred
for
lambda
with
early
return
with
integer
literal
in
one
of
possible
return
values
Issue: KT-20226
Short summary: since Kotlin 1.4, integer type returning from a lambda will be more specific for cases when
there is early return
Deprecation cycle:
>= 1.4: behavior changed, -XXLanguage:-NewInference can be used to temporarily revert to pre-1.4
behavior. Note that this flag will also disable several new language features.
Proper
capturing
of
star
projections
with
recursive
types
1114
Issue: KT-33012
Short summary: since Kotlin 1.4, more candidates will become applicable because capturing for recursive types
will work more correctly
Deprecation cycle:
>= 1.4: behavior changed, -XXLanguage:-NewInference can be used to temporarily revert to pre-1.4
behavior. Note that this flag will also disable several new language features.
Common
supertype
calculation
with
non-proper
type
and
flexible
one
leads
to
incorrect
results
Issue: KT-37054
Short summary: since Kotlin 1.4, common supertype between flexible types will be more specific protecting
from runtime errors
Deprecation cycle:
>= 1.4: behavior changed, -XXLanguage:-NewInference can be used to temporarily revert to pre-1.4
behavior. Note that this flag will also disable several new language features.
Type
safety
problem
because
of
lack
of
captured
conversion
against
nullable
type
argument
1115
Issue: KT-35487
Short summary: since Kotlin 1.4, subtyping between captured and nullable types will be more correct protecting
from runtime errors
Deprecation cycle:
>= 1.4: behavior changed, -XXLanguage:-NewInference can be used to temporarily revert to pre-1.4
behavior. Note that this flag will also disable several new language features.
Preserve
intersection
type
for
covariant
types
after
unchecked
cast
Issue: KT-37280
Short summary: since Kotlin 1.4, uchecked casts of covariant types produce the intersection type for smart
casts, not the type of the unchecked cast.
Deprecation cycle:
>= 1.4: behavior changed, -XXLanguage:-NewInference can be used to temporarily revert to pre-1.4
behavior. Note that this flag will also disable several new language features.
Type
variable
leaks
from
builder
inference
because
of
using
this
expression
1116
Issue: KT-32126
Short summary: since Kotlin 1.4, using this inside builder functions like sequence {} is prohibited if there are no
other proper constraints
Deprecation cycle:
>= 1.4: behavior changed, -XXLanguage:-NewInference can be used to temporarily revert to pre-1.4
behavior. Note that this flag will also disable several new language features.
Wrong
overload
resolution
for
contravariant
types
with
nullable
type
arguments
Issue: KT-31670
Short summary: since Kotlin 1.4, if two overloads of a function that takes contravariant type arguments differ
only by the nullability of the type (such as In<T> and In<T?>), the nullable type is considered more specific.
Deprecation cycle:
>= 1.4: behavior changed, -XXLanguage:-NewInference can be used to temporarily revert to pre-1.4
behavior. Note that this flag will also disable several new language features.
Builder
inference
with
non-nested
recursive
constraints
1117
Issue: KT-34975
Short summary: since Kotlin 1.4, builder functions such as sequence {} with type that depends on a recursive
constraint inside the passed lambda cause a compiler error.
Deprecation cycle:
>= 1.4: behavior changed, -XXLanguage:-NewInference can be used to temporarily revert to pre-1.4
behavior. Note that this flag will also disable several new language features.
Eager
type
variable
fixation
leads
to
a
contradictory
constraint
system
Issue: KT-25175
Short summary: since Kotlin 1.4, the type inference in certain cases works less eagerly allowing to find the
constraint system that is not contradictory.
Deprecation cycle:
>= 1.4: behavior changed, -XXLanguage:-NewInference can be used to temporarily revert to pre-1.4
behavior. Note that this flag will also disable several new language features.
Prohibit
tailrec
modifier
on
open
functions
1118
Issue: KT-18541
Short summary: since Kotlin 1.4, functions can't have open and tailrec modifiers at the same time.
Deprecation cycle:
< 1.4: report a warning on functions that have open and tailrec modifiers together (error in the progressive
mode).
The
INSTANCE
field
of
a
companion
object
more
visible
than
the
companion
object
class
itself
Issue: KT-11567
Component: Kotlin/JVM
Short summary: since Kotlin 1.4, if a companion object is private, then its field INSTANCE will be also private
Deprecation cycle:
< 1.4: the compiler generates object INSTANCE with a deprecated flag
Outer
finally
block
inserted
before
return
is
not
excluded
from
thecatch
interval
of
the
inner
try
block
without
finally
1119
Issue: KT-31923
Component: Kotlin/JVM
Short summary: since Kotlin 1.4, the catch interval will be computed properly for nested try/catch blocks
Deprecation cycle:
>= 1.4: behavior changed, -XXLanguage:-ProperFinally can be used to temporarily revert to pre-1.4 behavior
Use
the
boxed
version
of
an
inline
class
in
return
type
position
for
covariant
and
generic-specialized
overrides
Issues: KT-30419
Component: Kotlin/JVM
Short summary: since Kotlin 1.4, functions using covariant and generic-specialized overrides will return boxed
values of inline classes
Deprecation cycle:
Do
not
declare
checked
exceptions
in
JVM
bytecode
when
using
delegation
to
Kotlin
interfaces
1120
Issue: KT-35834
Component: Kotlin/JVM
Short summary: Kotlin 1.4 will not generate checked exceptions during interface delegation to Kotlin interfaces
Deprecation cycle:
Changed
behavior
of
signature-polymorphic
calls
to
methods
with
a
single
vararg
parameter
to
avoid
wrapping
the
argument
into
another
array
Issue: KT-35469
Component: Kotlin/JVM
Short summary: Kotlin 1.4 will not wrap the argument into another array on a signature-polymorphic call
Deprecation cycle:
Incorrect
generic
signature
in
annotations
when
KClass
is
used
as
a
generic
parameter
1121
Issue: KT-35207
Component: Kotlin/JVM
Short summary: Kotlin 1.4 will fix incorrect type mapping in annotations when KClass is used as a generic
parameter
Deprecation cycle:
Forbid
spread
operator
in
signature-polymorphic
calls
Issue: KT-35226
Component: Kotlin/JVM
Short summary: Kotlin 1.4 will prohibit the use of spread operator (*) on signature-polymorphic calls
Deprecation cycle:
< 1.4: report a warning on the use of a spread operator in signature-polymorphic calls
Change
initialization
order
of
default
values
for
tail-recursive
optimized
functions
1122
Issue: KT-31540
Component: Kotlin/JVM
Short summary: Since Kotlin 1.4, the initialization order for tail-recursive functions will be the same as for
regular functions
Deprecation cycle:
Do
not
generate
ConstantValue
attribute
for
non-const
vals
Issue: KT-16615
Component: Kotlin/JVM
Short summary: Since Kotlin 1.4, the compiler will not generate the ConstantValue attribute for non- const val s
Deprecation cycle:
Generated
overloads
for
@JvmOverloads
on
open
methods
should
be
final
1123
Issue: KT-33240
Components: Kotlin/JVM
Short summary: overloads for functions with @JvmOverloads will be generated as final
Deprecation cycle:
Lambdas
returning
kotlin.Result
now
return
boxed
value
instead
of
unboxed
Issue: KT-39198
Component: Kotlin/JVM
Short summary: since Kotlin 1.4, lambdas returning values of kotlin.Result type will return boxed value instead
of unboxed
Deprecation cycle:
Unify
exceptions
from
null
checks
1124
Issue: KT-22275
Component: Kotlin/JVM
Short summary: Starting from Kotlin 1.4, all runtime null checks will throw a java.lang.NullPointerException
Deprecation cycle:
< 1.4: runtime null checks throw different exceptions, such as KotlinNullPointerException,
IllegalStateException, IllegalArgumentException, and TypeCastException
>= 1.4: all runtime null checks throw a java.lang.NullPointerException. -Xno-unified-null-checks can be used
to temporarily revert to pre-1.4 behavior
Comparing
floating-point
values
in
array/list
operations
contains,
indexOf,
lastIndexOf:
IEEE
754
or
total
order
Issue: KT-28753
Short summary: the List implementation returned from Double/FloatArray.asList() will implement contains,
indexOf, and lastIndexOf, so that they use total order equality
Deprecation cycle:
Gradually
change
the
return
type
of
collection
min
and
max
functions
to
non-nullable
1125
Issue: KT-38854
Short summary: return type of collection min and max functions will be changed to non-nullable in 1.6
Deprecation cycle:
1.4: introduce ...OrNull functions as synonyms and deprecate the affected API (see details in the issue)
>=1.6: reintroduce the affected API but with non-nullable return type
Deprecate
appendln
in
favor
of
appendLine
Issue: KT-38754
Deprecation cycle:
1.4: introduce appendLine function as a replacement for appendln and deprecate appendln
Deprecate
conversions
of
floating-point
types
to
Short
and
Byte
1126
Issue: KT-30360
Short summary: since Kotlin 1.4, conversions of floating-point types to Short and Byte will be deprecated
Deprecation cycle:
Fail
fast
in
Regex.findAll
on
an
invalid
startIndex
Issue: KT-28356
Component: kotlin-stdlib
Short summary: since Kotlin 1.4, findAll will be improved to check that startIndex is in the range of the valid
position indices of the input char sequence at the moment of entering findAll, and throw
IndexOutOfBoundsException if it's not
Deprecation cycle:
Remove
deprecated
kotlin.coroutines.experimental
1127
Issue: KT-36083
Component: kotlin-stdlib
Short summary: since Kotlin 1.4, the deprecated kotlin.coroutines.experimental API is removed from stdlib
Deprecation cycle:
>= 1.4: kotlin.coroutines.experimental is removed from stdlib. On the JVM, a separate compatibility artifact
is provided (see details in the issue).
Remove
deprecated
mod
operator
Issue: KT-26654
Component: kotlin-stdlib
Short summary: since Kotlin 1.4, mod operator on numeric types is removed from stdlib
Deprecation cycle:
Hide
Throwable.addSuppressed
member
and
prefer
extension
instead
1128
Issue: KT-38777
Component: kotlin-stdlib
Deprecation cycle:
capitalize
should
convert
digraphs
to
title
case
Issue: KT-38817
Component: kotlin-stdlib
Short summary: String.capitalize() function now capitalizes digraphs from the Serbo-Croatian Gaj's Latin
alphabet in the title case (Ç… instead of Ç„)
Deprecation cycle:
Tools
Compiler
arguments
with
delimiter
characters
must
be
passed
in
double
quotes
on
Windows
1129
Issue: KT-30211
Component: CLI
Short summary: on Windows, kotlinc.bat arguments that contain delimiter characters (whitespace, =, ;, ,) now
require double quotes (")
Deprecation cycle:
>= 1.4: compiler arguments that contain delimiter characters (whitespace, =, ;, ,) require double quotes (")
KAPT:
Names
of
synthetic
$annotations()
methods
for
properties
have
changed
Issue: KT-36926
Component: KAPT
Short summary: names of synthetic $annotations() methods generated by KAPT for properties have changed in
1.4
Deprecation cycle:
< 1.4: names of synthetic $annotations() methods for properties follow the template
<propertyName>@annotations()
>= 1.4: names of synthetic $annotations() methods for properties include the get prefix:
get<PropertyName>@annotations()
Compatibility
guide
for
Kotlin
1.3
Keeping the Language Modern* and *Comfortable Updates are among the fundamental principles in Kotlin Language
Design. The former says that constructs which obstruct language evolution should be removed, and the latter says that
this removal should be well-communicated beforehand to make code migration as smooth as possible.
While most of the language changes were already announced through other channels, like update changelogs or compiler
warnings, this document summarizes them all, providing a complete reference for migration from Kotlin 1.2 to Kotlin 1.3.
1130
Basic
terms
In this document we introduce several kinds of compatibility:
Source: source-incompatible change stops code that used to compile fine (without errors or warnings) from compiling
anymore
Binary: two binary artifacts are said to be binary-compatible if interchanging them doesn't lead to loading or linkage
errors
Behavioral: a change is said to be behavioral-incompatible if one and the same program demonstrates different
behavior before and after applying the change
Remember that those definitions are given only for pure Kotlin. Compatibility of Kotlin code from the other languages
perspective (e.g. from Java) is out of the scope of this document.
Incompatible
changes
Evaluation
order
of
constructor
arguments
regarding
call
Issue: KT-19532
Component: Kotlin/JVM
Short summary: evaluation order with respect to class initialization is changed in 1.3
Deprecation cycle:
>= 1.3: behavior changed, -Xnormalize-constructor-calls=disable can be used to temporarily revert to pre-
1.3 behavior. Support for this flag is going to be removed in the next major release.
Missing
getter-targeted
annotations
on
annotation
constructor
parameters
1131
Issue: KT-25287
Component: Kotlin/JVM
Short summary: getter-target annotations on annotations constructor parameters will be properly written to
classfiles in 1.3
Deprecation cycle:
>=1.3: getter-target annotations on annotation constructor parameters are properly applied and written to
the generated code
Missing
errors
in
class
constructor’s
@get:
annotations
Issue: KT-19628
Deprecation cycle:
<1.2: compilation errors in getter-target annotations were not reported, causing incorrect code to be
compiled fine.
1.2.x: errors reported only by tooling, the compiler still compiles such code without any warnings
>=1.3: errors reported by the compiler too, causing erroneous code to be rejected
Nullability
assertions
on
access
to
Java
types
annotated
with
@NotNull
1132
Issue: KT-20830
Component: Kotlin/JVM
Short summary: nullability assertions for Java-types annotated with not-null annotations will be generated more
aggressively, causing code which passes null here to fail faster.
Deprecation cycle:
<1.3: the compiler could miss such assertions when type inference was involved, allowing potential null
propagation during compilation against binaries (see Issue for details).
>=1.3: the compiler generates missed assertions. This can cause code which was (erroneously) passing null
s here fail faster.
-XXLanguage:-StrictJavaNullabilityAssertions can be used to temporarily return to the pre-1.3 behavior.
Support for this flag will be removed in the next major release.
Unsound
smartcasts
on
enum
members
Issue: KT-20772
Short summary: a smartcast on a member of one enum entry will be correctly applied to only this enum entry
Deprecation cycle:
<1.3: a smartcast on a member of one enum entry could lead to an unsound smartcast on the same
member of other enum entries.
>=1.3: smartcast will be properly applied only to the member of one enum entry.
-XXLanguage:-SoundSmartcastForEnumEntries will temporarily return old behavior. Support for this flag will
be removed in the next major release.
val
backing
field
reassignment
in
getter
1133
Issue: KT-16681
Short summary: reassignment of the backing field of val -property in its getter is now prohibited
Deprecation cycle:
<1.2: Kotlin compiler allowed to modify backing field of val in its getter. Not only it violates Kotlin semantic,
but also generates ill-behaved JVM bytecode which reassigns final field.
1.2.X: deprecation warning is reported on code which reassigns backing field of val
Array
capturing
before
the
for-loop
where
it
is
iterated
Issue: KT-21354
Component: Kotlin/JVM
Short summary: if an expression in for-loop range is a local variable updated in a loop body, this change affects
loop execution. This is inconsistent with iterating over other containers, such as ranges, character sequences,
and collections.
Deprecation cycle:
<1.2: described code patterns are compiled fine, but updates to local variable affect loop execution
1.2.X: deprecation warning reported if a range expression in a for-loop is an array-typed local variable which
is assigned in a loop body
Nested
classifiers
in
enum
entries
1134
Issue: KT-16310
Short summary: since Kotlin 1.3, nested classifiers (classes, object, interfaces, annotation classes, enum
classes) in enum entries are prohibited
Deprecation cycle:
<1.2: nested classifiers in enum entries are compiled fine, but may fail with exception at runtime
Data
class
overriding
copy
Issue: KT-19618
Short summary: since Kotlin 1.3, data classes are prohibited to override copy()
Deprecation cycle:
<1.2: data classes overriding copy() are compiled fine but may fail at runtime/expose strange behavior
Inner
classes
inheriting
Throwable
that
capture
generic
parameters
from
the
outer
class
1135
Issue: KT-17981
Short summary: since Kotlin 1.3, inner classes are not allowed to inherit Throwable
Deprecation cycle:
<1.2: inner classes inheriting Throwable are compiled fine. If such inner classes happen to capture generic
parameters, it could lead to strange code patterns which fail at runtime.
Visibility
rules
regarding
complex
class
hierarchies
with
companion
objects
Short summary: since Kotlin 1.3, rules of visibility by short names are stricter for complex class hierarchies
involving companion objects and nested classifiers.
Deprecation cycle:
1.2.X: deprecation warnings reported on short names which are not going to be accessible anymore. Tooling
suggests automated migration by adding full name.
>=1.3: deprecation warnings elevated to errors. Offending code should add full qualifiers or explicit imports
Non-constant
vararg
annotation
parameters
1136
Issue: KT-23153
Short summary: since Kotlin 1.3, setting non-constant values as vararg annotation parameters is prohibited
Deprecation cycle:
<1.2: the compiler allows to pass non-constant value for vararg annotation parameter, but actually drops
that value during bytecode generation, leading to non-obvious behavior
Local
annotation
classes
Issue: KT-23277
Short summary: since Kotlin 1.3 local annotation classes are not supported
Deprecation cycle:
Smartcasts
on
local
delegated
properties
1137
Issue: KT-22517
Short summary: since Kotlin 1.3 smartcasts on local delegated properties are not allowed
Deprecation cycle:
<1.2: the compiler allowed to smartcast local delegated property, which could lead to unsound smartcast in
case of ill-behaved delegates
1.2.X: smartcasts on local delegated properries are reported as deprecated (the compiler issues warnings)
mod
operator
convention
Issues: KT-24197
Short summary: since Kotlin 1.3 declaration of mod operator is prohibited, as well as calls which resolve to
such declarations
Deprecation cycle:
1.1.X, 1.2.X: report warnings on declarations of operator mod, as well as on calls which resolve to it
1.3.X: elevate warnings to error, but still allow to resolve to operator mod declarations
Passing
single
element
to
vararg
in
named
form
1138
Issues: KT-20588, KT-20589. See also KT-20171
Short summary: in Kotlin 1.3, assigning single element to vararg is deprecated and should be replaced with
consecutive spread and array construction.
Deprecation cycle:
<1.2: assigning one value element to vararg in named form compiles fine and is treated as assigning single
element to array, causing non-obvious behavior when assigning array to vararg
1.2.X: deprecation warnings are reported on such assignments, users are suggested to switch to
consecutive spread and array construction.
>= 1.4: change semantic of assigning single element to vararg, making assignment of array equivalent to the
assignment of a spread of an array
Retention
of
annotations
with
target
EXPRESSION
Issue: KT-13762
Short summary: since Kotlin 1.3, only SOURCE retention is allowed for annotations with target EXPRESSION
Deprecation cycle:
<1.2: annotations with target EXPRESSION and retention other than SOURCE are allowed, but silently
ignored at use-sites
Annotations
with
target
PARAMETER
shouldn't
be
applicable
to
parameter's
type
1139
Issue: KT-9580
Short summary: since Kotlin 1.3, error about wrong annotation target will be properly reported when annotation
with target PARAMETER is applied to parameter's type
Deprecation cycle:
<1.2: aforementioned code patterns are compiled fine; annotations are silently ignored and not present in the
bytecode
Array.copyOfRange
throws
an
exception
when
indices
are
out
of
bounds
instead
of
enlarging
the
returned
array
Issue: KT-19489
Short summary: since Kotlin 1.3, ensure that the toIndex argument of Array.copyOfRange, which represents the
exclusive end of the range being copied, is not greater than the array size and throw IllegalArgumentException if
it is.
Deprecation cycle:
<1.3: in case toIndex in the invocation of Array.copyOfRange is greater than the array size, the missing
elements in range fill be filled with null s, violating soundness of the Kotlin type system.
>=1.3: check that toIndex is in the array bounds, and throw exception if it isn't
Progressions
of
ints
and
longs
with
a
step
of
Int.MIN_VALUE
and
Long.MIN_VALUE
are
outlawed
and
won’t
be
allowed
to
be
instantiated
1140
Issue: KT-17176
Short summary: since Kotlin 1.3, prohibit step value for integer progressions being the minimum negative value
of its integer type (Long or Int), so that calling IntProgression.fromClosedRange(0, 1, step = Int.MIN_VALUE) will
throw IllegalArgumentException
Deprecation cycle:
<1.3: it was possible to create an IntProgression with Int.MIN_VALUE step, which yields two values [0, -
2147483648], which is non-obvious behavior
>=1.3: throw IllegalArgumentException if the step is the minimum negative value of its integer type
Check
for
index
overflow
in
operations
on
very
long
sequences
Issue: KT-16097
Short summary: since Kotlin 1.3, make sure index, count and similar methods do not overflow for long
sequences. See the Issue for the full list of affected methods.
Deprecation cycle:
<1.3: calling such methods on very long sequences could produce negative results due to integer overflow
Unify
split
by
an
empty
match
regex
result
across
the
platforms
1141
Issue: KT-21049
Short summary: since Kotlin 1.3, unify behavior of split method by empty match regex across all platforms
Deprecation cycle:
<1.3: behavior of described calls is different when comparing JS, JRE 6, JRE 7 versus JRE 8+
Discontinued
deprecated
artifacts
in
the
compiler
distribution
Issue: KT-23799
Component: other
Short summary: Kotlin 1.3 discontinues the following deprecated binary artifacts:
Deprecation cycle:
1.2.X: the artifacts were marked as deprecated, the compiler reported warning on usage of those artifacts
Annotations
in
stdlib
1142
Issue: KT-21784
Short summary: Kotlin 1.3 removes annotations from the package org.jetbrains.annotations from stdlib and
moves them to the separate artifacts shipped with the compiler: annotations-13.0.jar and mutability-
annotations-compat.jar
Deprecation cycle:
Compatibility
modes
When a big team is migrating onto a new version, it may appear in a "inconsistent state" at some point, when some
developers have already updated, and others haven't. To prevent the former from writing and committing code that
others may not be able to compile, we provide the following command line switches (also available in the IDE and Gradle/
Maven):
-language-version X.Y- compatibility mode for Kotlin language version X.Y, reports errors for all language features that
came out later.
-api-version X.Y- compatibility mode for Kotlin API version X.Y, reports errors for all code using newer APIs from the
Kotlin Standard Library (including the code generated by the compiler).
Binary
compatibility
warnings
If you use the NV Kotlin compiler and have the OV standard library or the OV reflection library in the classpath, it can be a
sign that the project is misconfigured. To prevent unexpected problems during compilation or at runtime, we suggest
either updating the dependencies to NV, or specifying the API version / language version arguments explicitly. Otherwise,
the compiler detects that something can go wrong and reports a warning.
For example, if OV = 1.0 and NV = 1.1, you can observe one of the following warnings:
Runtime JAR files in the classpath have the version 1.0, which is older than the API version 1.1. Consider using the
runtime of version 1.1, or pass '-api-version 1.0' explicitly to restrict the available APIs to the runtime of version 1.0.
This means that you're using the Kotlin compiler 1.1 against the standard or reflection library of version 1.0. This can
be handled in different ways:
1143
If you intend to use the APIs from the 1.1 Standard Library, or language features that depend on those APIs, you
should upgrade the dependency to the version 1.1.
If you want to keep your code compatible with the 1.0 standard library, you can pass -api-version 1.0.
If you've just upgraded to Kotlin 1.1 but can not use new language features yet (e.g. because some of your
teammates may not have upgraded), you can pass -language-version 1.0, which will restrict all APIs and language
features to 1.0.
Runtime JAR files in the classpath should have the same version. These files were found in the classpath: kotlin-
reflect.jar (version 1.0) kotlin-stdlib.jar (version 1.1) Consider providing an explicit dependency on kotlin-reflect 1.1 to
prevent strange errors Some runtime JAR files in the classpath have an incompatible version. Consider removing them
from the classpath
This means that you have a dependency on libraries of different versions, for example the 1.1 standard library and the
1.0 reflection library. To prevent subtle errors at runtime, we recommend you to use the same version of all Kotlin
libraries. In this case, consider adding an explicit dependency on the 1.1 reflection library.
Some JAR files in the classpath have the Kotlin Runtime library bundled into them. This may cause difficult to debug
problems if there's a different version of the Kotlin Runtime library in the classpath. Consider removing these libraries
from the classpath
This means that there's a library in the classpath which does not depend on the Kotlin standard library as a
Gradle/Maven dependency, but is distributed in the same artifact with it (i.e. has it bundled). Such a library may cause
issues because standard build tools do not consider it an instance of the Kotlin standard library, thus it's not subject to
the dependency version resolution mechanisms, and you can end up with several versions of the same library in the
classpath. Consider contacting the authors of such a library and suggesting to use the Gradle/Maven dependency
instead.
Kotlin
Foundation
The Kotlin Foundation was created by JetBrains and Google with the mission to protect, promote and advance the
development of the Kotlin programming language. The Foundation secures Kotlin's development and distribution as Free
Software, meaning that it is able to be freely copied, modified and redistributed, including modifications to the official
versions.
Scope
The main functions of the Kotlin Foundation are:
Development. The code for the project is developed openly on GitHub primarily by the team employed at JetBrains, with
1144
contributions from Google and others. The Foundation has no developers on its payroll. The respective contributors hold
the copyright for the code they author. The code is distributed under the Apache License, Version 2.0.
Trademarks. The Kotlin trademark and associated marks, logos and domain names belong to the Kotlin Foundation. The
Foundation permits the usage of the trademarks according to the Kotlin Brand Usage Guidelines. All usages not
permitted automatically, require explicit written permission from the Foundation.
Lead Language Designer is in charge of all decisions regarding the development of the project and evolution of the
language. The Foundation appoints the Lead Language Designer, but does not directly make decisions about the course
of the project.
Incompatible changes. A special Language Committee appointed by the Foundation reviews the changes proposed by
the Lead Language Designer and has the power to reject incompatible changes or require certain deprecation procedures
to be carried out. The Language Committee has no power over compatible changes such as adding new features to the
language. Compatible changes are made at the sole discretion of the Lead Language Designer. The Committee maintains
a set of guidelines that are being consulted when making decisions. Meeting minutes of the Language Committee are
available online.
Structure
The Kotlin Foundation is a nonprofit nonstock corporation registered in the state of Delaware, USA. The Foundation is
governed by the Board of Directors that makes all decisions by voting. The Board appoints the Lead Language Designer
and the members of the Language Committee.
The President and the Secretary are elected by the Board of Directors as well. The President acts as the chief officer of
the Foundation and supervises its affairs and operations. The Secretary keeps record of all meetings of the Board and its
committees, and keeps track of membership and notices to the members, directors and third parties.
Current
personnel
President: Maxim Shafirov (JetBrains)
Board of Directors:
1145
Language Committee:
Language
Committee
guidelines
The Kotlin Language Committee has to approve every incompatible change before it lands in a stable version. The
committee determines whether the change is appropriate and motivated enough to be introduced and what deprecation
procedures have to be carried out to ensure comfortable migration for end users.
These guidelines describe the process the Committee follows and the criteria used for decision making. We realize that
these criteria can not be fully formalized and treat them as general guidelines, not a mechanical set of rules.
Review
process
Incompatible changes are submitted to the Language Committee by the Lead Language Designer. The Committee
evaluates the implications of such changes, considering the following:
Estimating
impact
When in doubt, we inspect large bodies of code available to us and test the implementations in EAP builds to collect
information about the expected impact of a change.
Proposals
A proposal is usually written by a developer responsible for the change or the relevant subsystems. See the Guide to
submitting incompatible changes.
When an issue has all the necessary details, it can be scheduled for review by the Language Committee. Approved
proposals are to be implemented by the development team and shipped in the appropriate stable release.
1146
Scope
Only features and components published as Stable are in the scope of Language Committee. Besides, the Language
Committee's scope is limited to the following:
The interop subsystem of the language: how foreign declarations are seen from Kotlin, and how Kotlin declarations are
seen from other languages
Compatibility of binary artifacts produced by kotlinc with one another and with other binaries (e.g. Java binaries)
Standard library: API and contracts of the declarations in kotlin-stdlib (and its extensions such as for kotlin-stdlib-jdk7)
KDoc syntax
For example, the following matters are out of scope for the Language Committee:
Also, see Appendix A for examples of changes that are not considered to be compatibility issues.
Migration
aids
and
deprecation
Normally, incompatible changes to stable features only land in feature releases. We announce the changes in a previous
release (it may be an incremental update to the previous feature release, but should allow enough time for users to
migrate their code).
The announcement is best done through compiler warnings, or in some cases IDE inspections and/or other tools. If
places in the code that should be changed in advance to prevent compatibility issues in the future can be detected
automatically, we announce the change and publish detection tools.
If the necessary changes to user code can be automated, we publish a migration tool along with the announcement.
Preferably, the IDE should suggest running the migration when it encounters deprecated constructs in the code.
1147
When automatic detection and/or migration is not practically possible, we publish instructions on how user code should
be adjusted.
Insignificant
changes
Some types of changes can be made without a deprecation cycle:
Small fixes that virtually no users will encounter can normally be made right away (but still require committee review)
Bugs causing compiler errors in good code can be fixed right away
Bugs causing bad code to compile, but always fail at runtime can be fixed right away
Incompatible
changes
to
the
language
The typical deprecation cycle for an incompatible language change:
The change planned for version B is announced in release notes to a previous version A
The compiler reports deprecation warnings (messages provide some guidance to possible replacements)
For eligible changes, the -progressive flag enables the change before version B (e.g. in version A or an incremental
update to it)
Version B ships with the change enabled (e.g. warnings turn into errors)
Migrations aids are kept available in the IDE
Backward compatibility flags in the compiler (-language-version and -api-version) support the behavior of version A
Future versions can remove migration aids and compatibility flags, but a version capable of automated migration
should be kept available for a reasonable amount of time
Incompatible
changes
to
the
libraries
The typical deprecation cycle for libraries:
The change planned for version B is announced in release notes to a previous version A
Relevant declarations are marked as @Deprecated(level = WARNING)
In some cases an optional support dependency that exposes the same API is published
1148
Changes
to
these
guidelines
Changes to these guidelines need to be approved by the Kotlin Language Committee.
Any proposed change needs to be published in advance providing a reasonable time to allow for comments on the
change by the Kotlin Community.
Appendix
A.
Examples
of
non-issues
The following cases are not considered to be compatibility issues and thus are out of scope for the Language Committee.
Changes
related
to
binaries
and
translation
A binary compiled against kotlin-stdlib fails to link or run because kotlin-stdlib is absent or outdated (older version than
used during compilation).
Adding generic parameters to existing declarations does not change the ABI on the JVM (due to erasure).
Changes to signatures of functions marked @InlineOnly are not changing the ABI on the JVM.
Source
language
changes
Code compilable with a newer version fails to compile with an older version (e.g. due to usages of new language
features).
The code breaks only if the user alters the build configuration or compiler settings explicitly (i.e. in addition to
advancing the compiler version).
Library
changes
Relaxing a contract on existing APIs.
Changes in toString() on other than Boolean, Numeric, and String types are not breaking changes.
Issues connected with loading of two different versions of the same library at runtime or link time.
Changes
affecting
performance
We recognize that runtime performance and bytecode size are important metrics, and will make reasonable effort to keep
them in a good shape, but we don't consider every slowdown (e.g. in edge cases or in very cold code) and every extra
byte in the classfile a breaking change.
1149
Appendix
B.
Assumptions
for
pragmatic
language
evolution
We make decisions on language changes under the assumption that most user code is designed with the following
considerations in mind. We do not optimize for smooth migration that disregards these considerations.
Availability
of
the
standard
library
All Kotlin code should be linked and run against the Standard Library of at least the same version as specified by the -api-
version upon compilation.
Type
inference
and
overload
resolution
algorithms
Improvements in type inference algorithms may result in more precise static types known for some expressions, this may
cause changes in overload resolution and even in signatures of declarations that don't specify return types explicitly.
Overloads of the same function should be intended to do the same thing. Language improvements may cause a different
overload to be selected in a new language version.
Declarations sensitive to API/ABI stability (e.g. public APIs) should specify return types explicitly. Language improvements
may cause a different type to be inferred for a given body expression. Also, some innocuous-looking changes in the
source code, done by the user, may cause similar effects.
Non-public
API
Internal declarations have no separate compilation guarantees. While sometimes accessible from other languages (e.g.
Java), declarations marked internal in Kotlin should not be called from outside the module they are declared in.
Private and synthetic declarations should not be relied upon. On some platforms, reflection has access to declarations
marked private and synthetic. We do not provide any compatibility guarantees for code that relies on such access.
Impedance
mismatches
across
language
boundaries
A Kotlin API exposed to another language may yield values that work in that language differently from Kotlin. For example,
Kotlin's unsigned integers will look signed for Java clients, and the programmer that works with the same API in the Java
code will be surprised by getting different result. While an undesirable situation, this is sometimes inevitable, and should
not be considered a breaking change (it does not fall under the intuitive definition of one anyway).
Guide
to
submitting
incompatible
changes
A proposal is usually written by a developer responsible for the change or the relevant subsystems. It has to be described
in the issue tracker and marked with the "for-language-committee" tag. To provide all the necessary details, issue in the
tracker should follow the template below.
1150
Issue
template
The issue should follow this template:
# Classification
# Background
> Optional section. Describe the background of the issue and possibly some motivation
# Existing behavior
> 1. (Minimal) code example
> 2. What's wrong with it
> 3. Detailed explanation of why and how this happens
> 4. Any known reasoning behind such behavior
> 5. Affected versions: when did the problem appear first?
# Proposed changes
> 1. Proposed changes
> 2. How it fixes the issue?
# Impact
> Examples of negative effects: changes of behavior, previously compiled code forbidden, etc.
> If possible:
> * number of impacted users
> * how common this pattern is
> * if we believe it's a rare case, why
> * is automated migration possible
# Migration plan
> Provide a detailed step-by-step migration plan
> Can the proposed changes be implemented immediately in the progressive mode?
Classification
The Classification section needs to classify the change, without describing its essence. The classification is used by the
Committee to quickly assess the severity of the issue. Here are the common categories to be used.
This section can be used as a checklist of things that need to be evaluated/thought of.
Type
of
change
Specify one or more of the following:
1151
Affecting ABI
Contract refinement
Motivation
types
Specify one or more of the following:
Type safety guarantees are not met (including fail-fast behavior for non-null types)
Redundant/outdated mechanism
1152
Impact
types
Compilation. Some code that used to compile won't compile any more
Such code always caused the compiler to fail with exception
Such code always threw an exception immediately upon execution or could not link
Such code inevitably caused exceptions to be thrown somewhere down the line after it was executed
Some of them may have been callable from other languages (Java/JS/C/Swift/...)
Behavior changes
Exceptions
Some exceptions may change their type or place, but all code that ran without exceptions keeps doing so
Some exceptions can be thrown earlier than before
Some exceptions change their type, but not the point of execution at which they are thrown
The new type is a subtype of the old one
Some code that compiled and ran without exceptions will throw exceptions in the new version
The behavior in question belongs under a previously released specification, contract or official documentation
By the contract, the old behavior is incorrect (thus a fix is needed)
The new behavior contradicts the contract (i.e. the contract has to be changed)
Some code may make more allocations or otherwise consume more memory
1153
The increase in code size is proportional to some parameters of the source
Detection
and
migration
modes
All code locations affected by this change can be accurately detected statically
Some, but not all code locations affected by this change can be accurately detected statically
Kotlin
brand
usage
guidelines
One of the goals of The Kotlin Foundation is to protect the use of the Kotlin word and to make sure it is not misused. The
following guidelines provide guidance on how to reference the Kotlin word trademark (“Trademarkâ€) in an approved
manner while ensuring the Trademark remains subject to protection under applicable laws around the world, and
continues to serve as a source indicator for the Kotlin programming language and related offerings.
Any use of the Trademark other than those described in these Guidelines must be approved in advance. Please contact
the Kotlin Foundation to request an express trademark license if you desire to use the Kotlin trademark, or a derivative of
the Kotlin trademark, in a manner not permitted under these Guidelines. To submit a usage request, please contact us,
clearly describing the intended usage and duration.
General
goals
We want the word Kotlin to refer to the Kotlin Programming Language, and we want to avoid it being used to refer to any
other programming language, or used in any way that may imply that the language is not free nor open source.
Permitted
uses
Given the open nature of Kotlin, you may use the Trademark to refer to the Kotlin programming language. Examples of
these references include the following:
1154
Contains the Kotlin programming language.
The use must be referential and describe the relationship of your products or services to the Kotlin programming
language.
Unpermitted
uses
The Trademark may never be used in a manner that would cause confusion as to JetBrains, Google, or the Kotlin
Foundation’s sponsorship, affiliation, or endorsement, including as part of a company name, product name, domain
name, or business trading name. Other than as allowed herein, the Kotlin word mark should not be combined with other
trademarks, terms, or source identifiers.
Under no circumstances can you claim any trademark rights in the Kotlin name or attempt to register a name or source
identifier that incorporates the Kotlin trademark or logo, or anything confusingly thereto, as a trademark, domain name,
business name or other source identifier.
Usage
guidelines
Please follow these guidelines when referencing the Trademark:
The first or most prominent mention of the Kotlin trademark should be immediately followed by the TM symbol. For
example "Kotlinâ„¢ ..." This requirement is waived in all contexts where such marks are not normally included, such as
non-marketing emails, online discussions, and academic papers. We encourage the use of the TM symbol whenever
possible, but recognize that many non-commercial and informal uses will omit it.
Where identifying that a product or service is built on the Kotlin programming language or runs the Kotlin programming
language, use the product’s own name followed by “in Kotlinâ„¢â€, “for Kotlinâ„¢â€, “compatible with
Kotlinâ„¢â€, “running Kotlin™†etc. Do not incorporate Kotlin into the product name.
User groups, communities and/or meet-ups should follow the naming convention " Kotlin User Group" where
represents the location and optionally other wordings. These entities should also prominently disclaim any affiliation
with or endorsement by The Kotlin Foundation.
Do not display the word Kotlin using any different stylization, color, or font from the surrounding text.
Don’t use the trademark as verb (“Kotlin your codeâ€), or create derivatives of it such as “Kotlinizeâ€, etc.
In certain usage context, and at the discretion of the Trademark Subcommittee of The Kotlin Foundation, you may
need to add a disclaimer on your site, publication, book, product, etc. where it clearly indicates that the product and/or
service provided is not associated with The Kotlin Foundation.
1155
Example
usages
User groups and Kotlin meetups A valid name for a user group could be “San Diego Kotlin User Group†If you’re
a user group or Kotlin meetup, please use the User Group assets provided.
Events If you’re organising a conference or educational event, you can use the word Kotlin to refer to the technology
that the event covers. However, Kotlin cannot be contained in the brand name for your conference or educational event
(such as KotlinConf or Kotlin Conference). Instead, you should use your own brand name, but indicate that it is a
conference for “Kotlin Language Users.†Your conference or educational event title also should not cause any
confusion or suggest any affiliation with or sponsorship by the Kotlin Foundation. Example of appropriate usages could
be “XYZ Conference for Kotlin†with XYZ being your own brand name.
Other commercial or non-commercial names Whether you’re referring to a product, company or service, you
shouldn’t incorporate Kotlin as your brand name, i.e. your company cannot be called “Kotlin Consulting†or
“Kotlin IDEâ€. It can however indicate that you provide consulting for the Kotlin programming language as part of the
description. For example, XYZ Consulting, which focuses on the Kotlin programming language.
Kotlin
Foundation
FAQ
How
can
I
contribute
or
provide
feedback
to
Kotlin?
Kotlin is an open source project, and there are many ways you can contribute:
Language features. Please use the Kotlin Evolution and Enhancement process (KEEP) if you'd like to make a proposal
for the Kotlin programming language.
Code contributions. Please refer to Contributions section at the Kotlin GitHub repository.
Filing issues or suggestions. Please use the Kotlin Issue Tracker to file issues or suggestions.
How
can
I
get
more
involved
with
the
Kotlin
community?
There are many online and in-person Kotlin communities. Please visit the Kotlin community page to see a list of user
groups, Kotlin nights and other ways that you can get involved!
How
is
the
Kotlin
Foundation
governed?
The Foundation is governed by the Board of Directors, who then appoint a president, Lead Language Designer and
members of the Language Committee. JetBrains and Google each delegate two directors to the board. The independent
member is elected by the rest of the board.
1156
Do
JetBrains
and
Google
contribute
financially
to
the
foundation?
Yes, to cover the operational and administrative expenses.
Does
the
foundation
generate
any
revenue?
No, Kotlin Foundation is a non-profit entity whose operational costs are covered by JetBrains and Google.
Can
I
license
the
Kotlin
trademark?
Yes. You are free to use the Kotlin trademark in accordance with our Kotlin brand usage guidelines. Any use of the
Trademark other than those described in the Guidelines must be approved in advance. If you need a specific license,
please refer to the request form
How
can
a
company
or
an
individual
join
the
foundation?
We are discussing possible ways for companies and individuals to participate, and will provide updates here in the future.
What
resources
should
I
follow
to
stay
up-to-date
on
Kotlin?
The best way to stay up-to-date on Kotlin is to visit the official Kotlin website, and follow the official Kotlin blog.
Security
We do our best to make sure our products are free of security vulnerabilities. To reduce the risk of introducing a
vulnerability, you can follow these best practices:
Always use the latest Kotlin release. For security purposes, we sign our releases published on Maven Central with
these PGP keys:
Fingerprint: 2FBA 29D0 8D2E 25EE 84C1 32C3 0729 A0AF F899 9A87
Use the latest versions of your application’s dependencies. If you need to use a specific version of a dependency,
periodically check if any new security vulnerabilities have been discovered. You can follow the guidelines from GitHub
or browse known vulnerabilities in the CVE base.
We are very eager and grateful to hear about any security issues you find. To report vulnerabilities that you discover in
Kotlin, please post a message directly to our issue tracker or send us an email.
1157
For more information on how our responsible disclosure process works, please check the JetBrains Coordinated
Disclosure Policy.
Kotlin
documentation
as
PDF
Here you can download a PDF version of Kotlin documentation that includes everything except tutorials and API
reference.
1158