Kotlin 1.2 introduced an experimental feature to create multiplatform projects. With multiplatform projects, it’s now possible to write common code in Kotlin, and share the code across different platforms, JVM and JS at the moment.
Let’s use a simple example to demonstrate how multiplatform projects work. The easiest way is to create a new Kotlin multiplatform project using IDEA 2017.3. I created a project called
calculator. IDEA created a Gradle project with two sub-projects:
calculator-js. The root project is the common module that contains code that is not specific to any platform, as well as declarations without implementation of platform-dependent APIs.
calculator-js are platform modules that contain implementations of platform-dependent declarations in the common module for a specific platform, as well as other platform-dependent code.
Let’s start from the
Calculator object in the common module.
Calculator has two functions
subtract as shared common API to be used on both platforms. Both functions use
log to output a log message.
log is a declaration to be implemented on both platforms.
expect means it expects a function
log to exist.
In a Kotlin file in the module
calculator-jvm, it implements the expected function
actual means it’s the actual implementation. This file uses
Calculator from the common module.
The Kotlin file in the module
calculator-js is similar, except that the function
log is implemented using
This new feature in Kotlin is trying to resolve the issue of sharing code between different platforms. If your application is targeting multiple platforms, then this new feature in Kotlin may be a good choice. Currently only JVM and JS platforms are supported, Native platform will be supported later.
For a typical Java-based web application, the server usually exposes REST APIs for browsers and mobile apps to invoke. Here are some examples that may be created as common modules.
Validations: Validations for REST requests can be shared between different platforms. The server side always needs to perform validations. In the client side code, we can reuse the same module to perform validations to give the user immediate feedback.
Business logic: Although it’s rare to put complex business logic in the client side code, some simple business logic can be put into a common module and shared by different platform modules.
Cross-cutting concerns, like logging and security, can be easily used in common modules and have platform specific implementations, similar to the logging example shown in the