Statistics
5
Views
0
Downloads
0
Donations
Support
Share
Uploader

高宏飞

Shared on 2026-02-13

AuthorKotlin

No description

Tags
No tags
Publisher: BigBrother
Language: 英文
File Format: PDF
File Size: 3.5 MB
Support Statistics
¥.00 · 0times
Text Preview (First 20 pages)
Registered users can read the full content for free

Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.

Kotlin Language Documentation
Table of Contents Overview Using Kotlin for Server-side Development Using Kotlin for Android Development Kotlin JavaScript Overview Kotlin/Native for Native Coroutines for asynchronous programming and more Multiplatform Programming What's New in Kotlin 1.1 What's New in Kotlin 1.2 What's New in Kotlin 1.3 Standard library Tooling Getting Started Basic Syntax Idioms Coding Conventions Basics Basic Types Packages Control Flow: if, when, for, while Returns and Jumps Classes and Objects Classes and Inheritance Properties and Fields Interfaces Visibility Modifiers Extensions 7 7 9 11 13 15 16 19 30 39 45 47 48 48 55 60 78 78 88 90 94 97 97 105 109 112 115 2
Data Classes Sealed Classes Generics Nested and Inner Classes Enum Classes Object Expressions and Declarations Inline classes Delegation Delegated Properties Functions and Lambdas Functions Higher-Order Functions and Lambdas Inline Functions Collections Kotlin Collections Overview Constructing Collections Iterators Ranges and Progressions Sequences Collection Operations Overview Collection Transformations Filtering plus and minus Operators Grouping Retrieving Collection Parts Retrieving Single Elements Collection Ordering Collection Aggregate Operations Collection Write Operations 120 122 123 130 131 133 138 143 145 152 152 159 167 171 171 176 179 181 183 186 188 192 195 196 197 200 203 206 208 3
List Specific Operations Set Specific Operations Map Specific Operations Multiplatform Programming Platform-Specific Declarations Building Multiplatform Projects with Gradle Other Destructuring Declarations Type Checks and Casts: 'is' and 'as' This Expression Equality Operator overloading Null Safety Exceptions Annotations Reflection Scope Functions Type-Safe Builders Experimental API Markers Reference Keywords and Operators Grammar Java Interop Calling Java code from Kotlin Calling Kotlin from Java JavaScript Dynamic Type Calling JavaScript from Kotlin 210 215 216 220 220 222 260 260 263 267 268 269 274 278 281 286 291 299 306 312 312 318 337 337 351 362 362 364 4
Calling Kotlin from JavaScript JavaScript Modules JavaScript Reflection JavaScript DCE Example Native Concurrency in Kotlin/Native Immutability in Kotlin/Native Kotlin/Native libraries Advanced topics Platform libraries Kotlin/Native interoperability Kotlin/Native interoperability with Swift/Objective-C CocoaPods integration Kotlin/Native Gradle plugin Coroutines Table of contents Additional references Coroutine Basics Cancellation and Timeouts Composing Suspending Functions Coroutine Context and Dispatchers Asynchronous Flow Channels Exception Handling Shared mutable state and concurrency Select Expression (experimental) Tools Documenting Kotlin Code 367 370 374 375 376 377 377 381 382 383 385 386 397 404 407 426 426 426 427 433 438 443 454 477 486 495 501 508 508 5
Annotation Processing with Kotlin Using Gradle Using Maven Using Ant Kotlin and OSGi Compiler Plugins Code Style Migration Guide Evolution Kotlin Evolution Stability of Different Components Compatibility Guide for Kotlin 1.3 FAQ FAQ Comparison to Java Programming Language 512 517 526 534 538 540 547 550 550 556 557 570 570 574 6
Overview 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. 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. Using Kotlin for Server-side Development — — — — — — Frameworks for Server-side Development with Kotlin — — — — 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 Kotlin- compiled classes to the requirements of the framework. 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. 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. 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. — Deploying Kotlin Server-side Applications Users of Kotlin on the Server Side Next Steps — — 8
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 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. The Kotlin team o ers a set of tools for Android development that goes beyond the standard language features: 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. Using Kotlin for Android Development — — — — — — Kotlin for Android Case Studies — — — Tools for Android Development — 9
Anko is a library providing a set of Kotlin-friendly wrappers around the Android APIs, as well as a DSL that lets you replace your layout .xml les with Kotlin code. Download and install Android Studio which includes Kotlin support out of the box. 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. — Next Steps — — — — — 10
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). 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. Kotlin JavaScript Overview — — — — How it can be used — — — — — 11
To nd out how to start using Kotlin for JavaScript, please refer to the tutorials. Getting Started with Kotlin to JavaScript 12
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. 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. 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) 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. Kotlin/Native for Native Why Kotlin/Native? Target Platforms — — — — — — Interoperability — — — — — 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. 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, server- side, 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. 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. Sharing Code between Platforms How to Start — — — — — — — — — — — — 14
Asynchronous or non-blocking programming is the new reality. Whether we're creating server- side, 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. 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 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 Coroutines for asynchronous programming and more How to Start — — — — — — — — — — 15
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. 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") } Multiplatform Programming How it works 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. 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. 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 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. Tutorials and Documentation New to Kotlin? Take a look at the Getting Started page. Suggested documentation pages: Multiplatform Libraries Use cases Android — iOS Client — Server How to start 17
Setting up a Multiplatform Project Platform-Speci c Declarations Recommended tutorials: Multiplatform Kotlin Library Multiplatform Project: iOS and Android Example Projects KotlinConf app KotlinConf Spinner app Even more examples are on GitHub — — — — — — 18
Coroutines Other language features Standard library JVM backend JavaScript backend 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 front-end development environment. See below for a more detailed list of changes. 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 speci c programming paradigm or concurrency library. A coroutine is e ectively 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). Let's look at async / await which is implemented in an external library, kotlinx.coroutines: // runs the code in the background thread pool fun asyncOverlay() = async(CommonPool) { // start two async operations val original = asyncLoadImage("original") val overlay = asyncLoadImage("overlay") // and then apply overlay to both results applyOverlay(original.await(), overlay.await()) } // launches new coroutine in UI context launch(UI) { // wait for async overlay to complete val image = asyncOverlay().await() // 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 di erent thread) when the operation being awaited completes. What's New in Kotlin 1.1 Table of Contents — — — — — JavaScript Coroutines (experimental) 19
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: val seq = buildSequence { for (i in 1..5) { // yield a square of i yield(i * i) } // yield a range yieldAll(26..28) } // print the sequence intln(seq.toList()) Run the code above to see the result. Feel free to edit it and run again! For more information, please refer to the coroutine 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 nal 1.1 release. A type alias allows you to de ne 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: typealias OscarWinners = Map<String, String> fun countLaLaLand(oscarWinners: OscarWinners) = oscarWinners.count { it.value.contains("La La Land") } // Note that the type names (initial and the type alias) are interchangeable: fun checkLaLaLandIsTheBestMovie(oscarWinners: Map<String, String>) = oscarWinners["Best picture"] == "La La Land" See the documentation and KEEP for more details. You can now use the :: operator to get a member reference pointing to a method or property of a speci c object instance. Previously this could only be expressed with a lambda. Here's an example: val numberRegex = "\\d+".toRegex() val numbers = listOf("abc", "123", "456").filter(numberRegex::matches) Other Language Features Type aliases Bound callable references 20