In this tutorial, we will learn how to set up a project that supports multiple platforms using Kotlin Multiplatform. You will learn how to set up a basic project structure, write shared code, and implement platform-specific functionalities.
Open IntelliJ IDEA and create a new Kotlin Multiplatform Project.
Choose the platforms you want to support. For this tutorial, we will select JVM and JS.
Name your project and click 'Finish'.
The generated project includes several modules:
shared
: This module contains code that is shared between platforms.
jvmMain
: This module is for JVM platform-specific code.
jsMain
: This module is for JS platform-specific code.
Shared code goes in the shared
module. Here, you can define classes, functions, and interfaces that will be used across all platforms.
Platform-specific code goes in the respective jvmMain
and jsMain
modules. Here, you can implement platform-specific functionalities.
In the shared
module, create a new file Shared.kt
and write the following code:
expect class Platform() {
val platform: String
}
This expect
keyword tells Kotlin that the actual implementation will be provided in each platform module.
In the jvmMain
module, create a new file Platform.kt
:
actual class Platform actual constructor() {
actual val platform: String = "JVM"
}
In the jsMain
module, create another Platform.kt
file:
actual class Platform actual constructor() {
actual val platform: String = "JS"
}
The actual
keyword tells Kotlin that this is the implementation of an expected declaration.
In the main
function of each platform module, you can use the Platform
class:
fun main() {
println("Hello from ${Platform().platform}")
}
This will print "Hello from JVM" when run in the JVM module and "Hello from JS" when run in the JS module.
In this tutorial, you learned how to set up a Kotlin Multiplatform project, write shared code, and implement platform-specific functionalities.
Next, you could explore how to use the Kotlinx.serialization library to serialize and deserialize data in a multiplatform project.
Create a new Kotlin Multiplatform project that supports JVM, JS, and Native. Write a shared function that returns the current date and time, and implement it differently for each platform.
Extend the previous exercise by serializing the date and time into JSON format.
You can use the Date
class in JVM, the Date
object in JS, and the posix
function in Native to get the current date and time.
You can use the Json
class from kotlinx.serialization to serialize the date and time.
Remember, practice makes better. Keep exploring and happy coding!