Kotlin 多平台

多平台项目处于 Alpha版。语言特性与工具都可能在未来的 Kotlin 版本中发生变化。

支持多平台程序设计是 Kotlin 的主要优势之一。 它减少了为不同平台编写与维护相同代码所花的时间,同时保留了原生编程的灵活性与优势。

Kotlin Multiplatform use cases

Android and iOS applications

Sharing code between mobile platforms is one of the major Kotlin Multiplatform use cases. With Kotlin Multiplatform Mobile, you can build cross-platform mobile applications and share common code between Android and iOS, such as business logic, connectivity, and more.

Check out the Get started with Kotlin Multiplatform Mobile section and Kotlin Multiplatform Hands-on: Networking and Data Storage, where you will create an application for Android and iOS that includes a module with shared code for both platforms.

Full-stack web applications

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.

See Build a Full Stack Web App with Kotlin Multiplatform hands-on, where you will create a connected application consisting of a server part, using Kotlin/JVM and a web client, using Kotlin/JS.

Multiplatform libraries

Kotlin Multiplatform is also useful for library authors. You can create a multiplatform library with common code and its platform-specific implementations for JVM, JS, and Native platforms. Once published, a multiplatform library can be used in other cross-platform projects as a dependency.

See the Create and publish a multiplatform library tutorial, where you will create a multiplatform library, test it, and publish it to Maven.

Common code for mobile and web applications

One more popular case for using Kotlin Multiplatform is sharing the same code across Android, iOS, and web apps. It reduces the amount of business logic coded by frontend developers and helps implement products more efficiently, decreasing the coding and testing efforts.

See the RSS Reader sample project — a cross-platform application for iOS and Android with desktop and web clients implemented as experimental features.

Kotlin 多平台的工作原理

Kotlin 多平台

  • 公共 Kotlin 包括语言、核心库与基本工具。 用公共 Kotlin 编写的代码适用于所有平台的各个地方。
  • 借助 Kotlin 多平台库,可以在公共代码以及平台相关代码中复用多平台逻辑。 公共代码可以依赖一组涵盖日常任务的库,例如 HTTP序列化(serialization)管理协程(coroutines)
  • 如需与平台互操作,请使用平台相关的 Kotlin 版本。平台相关的 Kotlin 版本 (Kotlin/JVM、 Kotlin/JS、 Kotlin/Native)包含对 Kotlin 语言的扩展以及平台相关的库与工具。
  • 通过这些平台可以访问平台原生代码(JVM、 JS 与 Native)并利用所有原生功能。

Code sharing between platforms

使用 Kotlin 多平台,花更少的时间为不同平台编写并维护相同的代码 ——只需使用 Kotlin 提供的机制进行共享即可:

Get started

New to Kotlin? Take a look at Getting started with Kotlin.

样例项目

Look through cross-platform application samples to understand how Kotlin Multiplatform works: