Solution: Migrating a Kotlin/JVM project to KMP
First, you need to transform the build.gradle.kts
configuration to Kotlin Multiplatform, and change the "kotlin("jvm")" plugin to "kotlin("multiplatform")". Then, you need to configure the targets. This is what this configuration might look like:
plugins {
kotlin("multiplatform") version "1.8.0"
application
}
group = "org.example"
version = "1.0-SNAPSHOT"
repositories {
mavenCentral()
}
kotlin {
jvm {
withJava()
}
js(IR) {
moduleName = "sudoku-generator"
browser()
binaries.library()
}
sourceSets {
val commonMain by getting {
dependencies {
implementation(
"org.jetbrains.kotlinx:kotlinx-coroutines-core:1.6.4")
}
}
val commonTest by getting {
dependencies {
implementation(kotlin("test"))
}
}
val jvmMain by getting
val jvmTest by getting
val jsMain by getting
val jsTest by getting
}
}
Now move all your code from src/main/kotlin
to src/commonMain/kotlin
. Then move all your tests from src/test/kotlin
to src/commonTest/kotlin
.
In the tests, you need to replace the test annotations with those from the kotlin-test library.
You need to add a src/jsMain/kotlin
folder and create a SudokuGeneratorJs.kt
file in it. It could contain the following code:
@file:OptIn(ExperimentalJsExport::class)
import generator.SudokuGenerator
import solver.SudokuSolver
@JsExport
@JsName("SudokuGenerator")
class SudokuGeneratorJs {
private val generator = SudokuGenerator()
private val solver = SudokuSolver()
fun generateSudoku() = generator
.generate(solver)
.let {
Sudoku(it.solved.toJs(), it.sudoku.toJs())
}
}
@JsExport
class Sudoku(
val solved: Array<Array<Int?>>,
val sudoku: Array<Array<Int?>>
)
fun SudokuState.toJs(): Array<Array<Int?>> = List(9) { row ->
List(9) { col ->
val cell = this.cells[SudokuState.Position(row, col)]
when (cell) {
is SudokuState.CellState.Filled -> cell.value
is SudokuState.CellState.Empty, null -> null
}
}.toTypedArray()
}.toTypedArray()
Marcin Moskala is a highly experienced developer and Kotlin instructor as the founder of Kt. Academy, an official JetBrains partner specializing in Kotlin training, Google Developers Expert, known for his significant contributions to the Kotlin community. Moskala is the author of several widely recognized books, including "Effective Kotlin," "Kotlin Coroutines," "Functional Kotlin," "Advanced Kotlin," "Kotlin Essentials," and "Android Development with Kotlin."
Beyond his literary achievements, Moskala is the author of the largest Medium publication dedicated to Kotlin. As a respected speaker, he has been invited to share his insights at numerous programming conferences, including events such as Droidcon and the prestigious Kotlin Conf, the premier conference dedicated to the Kotlin programming language.