kotlin-docs.pdf - Kotlin Language Documentation Table of...

This preview shows page 1 out of 586 pages.

Unformatted text preview: Kotlin Language Documentation Table of Contents Overview 7 Using Kotlin for Server-side Development 7 Using Kotlin for Android Development 9 Kotlin JavaScript Overview 11 Kotlin/Native for Native 13 Coroutines for asynchronous programming and more 15 Multiplatform Programming 16 What's New in Kotlin 1.1 19 What's New in Kotlin 1.2 30 What's New in Kotlin 1.3 39 Standard library 45 Tooling 47 Getting Started 48 Basic Syntax 48 Idioms 55 Coding Conventions 61 Basics 79 Basic Types 79 Packages 89 Control Flow: if, when, for, while 91 Returns and Jumps 95 Classes and Objects 98 Classes and Inheritance 98 Properties and Fields 106 Interfaces 110 Visibility Modifiers 113 Extensions 116 2 Data Classes 121 Sealed Classes 123 Generics 124 Nested and Inner Classes 131 Enum Classes 132 Object Expressions and Declarations 134 Inline classes 139 Delegation 144 Delegated Properties 146 Functions and Lambdas 153 Functions 153 Higher-Order Functions and Lambdas 160 Inline Functions 168 Collections 172 Kotlin Collections Overview 172 Constructing Collections 177 Iterators 180 Ranges and Progressions 182 Sequences 184 Collection Operations Overview 187 Collection Transformations 189 Filtering 193 plus and minus Operators 196 Grouping 197 Retrieving Collection Parts 198 Retrieving Single Elements 201 Collection Ordering 204 Collection Aggregate Operations 207 Collection Write Operations 209 3 List Specific Operations 211 Set Specific Operations 216 Map Specific Operations 217 Multiplatform Programming 221 Platform-Specific Declarations 221 Building Multiplatform Projects with Gradle 223 Other 261 Destructuring Declarations 261 Type Checks and Casts: 'is' and 'as' 264 This Expression 268 Equality 269 Operator overloading 270 Null Safety 275 Exceptions 279 Annotations 282 Reflection 287 Scope Functions 292 Type-Safe Builders 300 Experimental API Markers 307 Reference 313 Keywords and Operators 313 Grammar 319 Java Interop 338 Calling Java code from Kotlin 338 Calling Kotlin from Java 352 JavaScript 363 Dynamic Type 363 Calling JavaScript from Kotlin 365 4 Calling Kotlin from JavaScript 368 JavaScript Modules 371 JavaScript Reflection 375 JavaScript DCE 376 Example 377 Native 378 Concurrency in Kotlin/Native 378 Immutability in Kotlin/Native 382 Kotlin/Native libraries 383 Advanced topics 384 Platform libraries 386 Kotlin/Native interoperability 387 Kotlin/Native interoperability with Swift/Objective-C 398 CocoaPods integration 405 Kotlin/Native Gradle plugin 408 Coroutines 427 Table of contents 427 Additional references 427 Coroutine Basics 428 Cancellation and Timeouts 434 Composing Suspending Functions 439 Coroutine Context and Dispatchers 444 Asynchronous Flow 455 Channels 478 Exception Handling 487 Shared mutable state and concurrency 496 Select Expression (experimental) 502 Tools 509 Documenting Kotlin Code 509 5 Annotation Processing with Kotlin 513 Kotlin Compiler Options 518 Using Gradle 526 Using Maven 535 Using Ant 543 Kotlin and OSGi 547 Compiler Plugins 549 Code Style Migration Guide 556 Evolution 559 Kotlin Evolution 559 Stability of Different Components 565 Compatibility Guide for Kotlin 1.3 566 FAQ 579 FAQ 579 Comparison to Java Programming Language 583 6 Overview Using Kotlin for Server-side Development Kotlin is a great t 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 bene ts 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 o ers framework-speci c 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 rst steps. Kotlin Koans o er 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 o er more concise APIs, starting with version 5.0. The online project generator allows you to quickly generate a new project in Kotlin. — Vert.x, a framework for building reactive Web applications on the JVM, o ers 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 o ering 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. 7 — 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 Kotlincompiled 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 o cial Heroku tutorial. AWS Labs provides a sample project showing the use of Kotlin for writing AWS Lambda functions. Google Cloud Platform o ers 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 — The Creating Web Applications with Http Servlets and Creating a RESTful Web Service with Spring Boot tutorials show you how you can build and run very small Web applications in Kotlin. — For a more in-depth introduction to the language, check out the reference documentation on this site and Kotlin Koans. 8 Using Kotlin for Android Development Kotlin is a great t for developing Android applications, bringing all of the advantages of a modern language to the Android platform without introducing any new restrictions: — Compatibility: Kotlin is fully compatible with JDK 6, ensuring that Kotlin applications can run on older Android devices with no issues. The Kotlin tooling is fully supported in Android Studio and compatible with the Android build system. — Performance: A Kotlin application runs as fast as an equivalent Java one, thanks to very similar bytecode structure. With Kotlin's support for inline functions, code using lambdas often runs even faster than the same code written in Java. — Interoperability: Kotlin is 100% interoperable with Java, allowing to use all existing Android libraries in a Kotlin application. This includes annotation processing, so databinding and Dagger work too. — Footprint: Kotlin has a very compact runtime library, which can be further reduced through the use of ProGuard. In a real application, the Kotlin runtime adds only a few hundred methods and less than 100K to the size of the .apk le. — Compilation Time: Kotlin supports e cient incremental compilation, so while there's some additional overhead for clean builds, incremental builds are usually as fast or faster than with Java. — 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 rst steps. Kotlin Koans o er a guide through the key features of the language with a series of interactive exercises. Kotlin for Android Case Studies Kotlin has been successfully adopted by major companies, and a few of them have shared their experiences: — Pinterest has successfully introduced Kotlin into their application, used by 150M people every month. — Basecamp's Android app is 100% Kotlin code, and they report a huge di erence in programmer happiness and great improvements in work quality and speed. — Keepsafe's App Lock app has also been converted to 100% Kotlin, leading to a 30% decrease in source line count and 10% decrease in method count. Kotlin Android Extensions Kotlin Android Extensions is a compiler extension that allows you to get rid of findViewById() calls in your code and to replace them with synthetic compiler-generated properties. Next Steps — Download and install Android Studio which includes Kotlin support out of the box. 9 — Follow the Getting Started with Android and Kotlin tutorial to create your rst Kotlin application. — For a more in-depth introduction, check out the reference documentation on this site and Kotlin Koans. — Another great resource is Kotlin for Android Developers, a book that guides you step by step through the process of creating a real Android application in Kotlin. — Check out Google's sample projects written in Kotlin. 10 Kotlin JavaScript Overview Kotlin provides the ability to target JavaScript. It does so by transpiling Kotlin to JavaScript. The current implementation targets ECMAScript 5.1 but there are plans to eventually target ECMAScript 2015 as well. When you choose the JavaScript target, any Kotlin code that is part of the project as well as the standard library that ships with Kotlin is transpiled to JavaScript. However, this excludes the JDK and any JVM or Java framework or library used. Any le that is not Kotlin will be ignored during compilation. The Kotlin compiler tries to comply with the following goals: — Provide output that is optimal in size — Provide output that is readable JavaScript — Provide interoperability with existing module systems — Provide the same functionality in the standard library whether targeting JavaScript or the JVM (to the largest possible degree). How it can be used You may want to compile Kotlin to JavaScript in the following scenarios: — Creating Kotlin code that targets client-side JavaScript — Interacting with DOM elements. Kotlin provides a series of statically typed interfaces to interact with the Document Object Model, allowing creation and update of DOM elements. — Interacting with graphics such as WebGL. You can use Kotlin to create graphical elements on a web page using WebGL. — Creating Kotlin code that targets server-side JavaScript — Working with server-side technology. You can use Kotlin to interact with server-side JavaScript such as Node.js Kotlin can be used together with existing third-party libraries and frameworks, such as jQuery or React. To access third-party frameworks with a strongly-typed API, you can convert TypeScript de nitions from the De nitely Typed type de nitions repository to Kotlin using the dukat tool. Alternatively, you can use the dynamic type to access any framework without strong typing. JetBrains develops and maintains several tools speci cally for the React community: React bindings as well as Create React Kotlin App. The latter helps you start building React apps with Kotlin with no build con guration. Kotlin is compatible with CommonJS, AMD and UMD, making interaction with di erent module systems straightforward. 11 Getting Started with Kotlin to JavaScript To nd out how to start using Kotlin for JavaScript, please refer to the tutorials. 12 Kotlin/Native for Native 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: — iOS (arm32, arm64, simulator x86_64) — MacOS (x86_64) — Android (arm32, arm64) — Windows (mingw x86_64, x86) — Linux (x86_64, arm32, MIPS, MIPS little endian, Raspberry Pi) — WebAssembly (wasm32) Interoperability Kotlin/Native supports two-way interoperability with the Native world. On the one hand, the compiler creates: — an executable for many platforms — a static library or dynamic library with C headers for C/C++ projects — an Apple framework for Swift and Objective-C projects On the other hand, Kotlin/Native supports interoperability to use existing libraries directly from Kotlin/Native: — static or dynamic C Libraries — C, Swift, and Objective-C frameworks 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. 13 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 package. Sharing Code between Platforms Multiplatform projects are supported between di erent Kotlin and Kotlin/Native targets. This is the way to share common Kotlin code between many platforms, including Android, iOS, serverside, JVM, client-side, JavaScript, CSS, and native. Multiplatform libraries provide the necessary APIs for the common Kotlin code and help to develop shared parts of a project in Kotlin code once and share it with all of the target platforms. How to Start Tutorials and Documentation New to Kotlin? Take a look at the Getting Started page. Suggested documentation pages: — C interop — Swift/Objective-C interop Recommended tutorials: — A basic Kotlin/Native application — Multiplatform Project: iOS and Android — Types mapping between C and Kotlin/Native — Kotlin/Native as a Dynamic Library — Kotlin/Native as an Apple Framework Example Projects — Kotlin/Native sources and examples — KotlinConf app — KotlinConf Spinner app — Kotlin/Native sources and examples (.tgz) — Kotlin/Native sources and examples (.zip) Even more examples are on GitHub. 14 Coroutines for asynchronous programming and more Asynchronous or non-blocking programming is the new reality. Whether we're creating serverside, desktop or mobile applications, it's important that we provide an experience that is not only uid from the user's perspective, but scalable when needed. There are many approaches to this problem, and in Kotlin we take a very exible one by providing Coroutine support at the language level and delegating most of the functionality to libraries, much in line with Kotlin's philosophy. As a bonus, coroutines not only open the doors to asynchronous programming, but also provide a wealth of other possibilities such as concurrency, actors, etc. How to Start Tutorials and Documentation New to Kotlin? Take a look at the Getting Started page. Selected documentation pages: — Coroutines Guide — Basics — Channels — Coroutine Context and Dispatchers — Shared Mutable State and Concurrency — Asynchronous Flow Recommended tutorials: — Your rst coroutine with Kotlin — Asynchronous Programming — Introduction to Coroutines and Channels hands-on lab Example Projects — kotlinx.coroutines Examples and Sources — KotlinConf app Even more examples are on GitHub 15 Multiplatform Programming Multiplatform projects are an experimental feature in Kotlin 1.2 and 1.3. All of the language and tooling features described in this document are subject to change in future Kotlin versions. Working on all platforms is an explicit goal for Kotlin, but we see it as a premise to a much more important goal: sharing code between platforms. With support for JVM, Android, JavaScript, iOS, Linux, Windows, Mac and even embedded systems like STM32, Kotlin can handle any and all components of a modern application. And this brings the invaluable bene t of reuse for code and expertise, saving the e ort for tasks more challenging than implementing everything twice or multiple times. How it works Overall, multiplatform is not about compiling all code for all platforms. This model has its obvious limitations, and we understand that modern applications need access to unique features of the platforms they are running on. Kotlin doesn't limit you to the common subset of all APIs in the world. Every component can share as much code as needed with others but can access platform APIs at any time through the expect/actual mechanism provided by the language. Here's an example of code sharing and interaction between the common and platform logic in a minimalistic logging framework. The common code would look like this: enum class LogLevel { DEBUG, WARN, ERROR } internal expect fun writeLogMessage(message: String, logLevel: LogLevel) fun logDebug(message: String) = writeLogMessage(message, LogLevel.DEBUG) fun logWarn(message: String) = writeLogMessage(message, LogLevel.WARN) fun logError(message: String) = writeLogMessage(message, LogLevel.ERROR) ├ compiled for all platforms ├ expected platform-specific API ├ expected API can be used in the common code It expects the targets to provide platform-speci c implementations for writeLogMessage , and the common code can now use this declaration without any consideration of how it is implemented. On the JVM, one could provide an implementation that writes the log to the standard output: internal actual fun writeLogMessage(message: String, logLevel: LogLevel) { println("[$logLevel]: $message") } 16 In the JavaScript world, a completely di erent set of APIs is availiable, so one could instead implement logging to the console: 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) } } In 1.3 we reworked the entire multiplatform model. The new DSL we have for describing multiplatform Gradle projects is much more exible, and we'll keep working on it to make project con guration straightforward. Multiplatform Libraries Common code can rely on a set of libraries that cover everyday tasks such as HTTP, serialization, and managing coroutines. Also, an extensive standard library is available on all platforms. You can always write your own library providing a common API and implementing it di erently on every platform. Use cases Android — iOS Sharing code between mobile platforms is one of the major Kotlin Multiplatform use cases, and it is now possible to build mobile applications with parts of the code, such as business logic, connectivity, and more, shared between Android and iOS. See: Multiplatform Project: iOS and Android Client — Server Another scenario when code sharing may bring bene ts is a connected application where the logic may 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. How to start Tutorials and Documentation ...
View Full Document

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture