CodeBlanks Logo Icon CodeBlanks

KMP

Write a shared module with Kotlin Multiplatform.

Shared module with KMP

The second lesson adds the Note data class, which represents the shared module of KMP. This class lives in commonMain; every target uses it.

Example: data class Note(val id: Int, val title: String). A data class auto-generates equals, hashCode and copy. This is the basis of the shared data model. In main you create a Note and print its title. In the next lesson you will extend this class with code generation.

Using the Note model

To create a Note you call the constructor: Note(1, "Merhaba"). Properties are accessed with a dot: n.title.

Thanks to data class, two Notes are equal if their fields match. The copy method produces a copy with one field changed: n.copy(title = "Yeni"). This is the safe way to update shared data. In this lesson main creates a Note and prints its title.

Practice Add the Note class

Define data class Note(val id: Int, val title: String). In main, do val n = Note(1, "Merhaba") and write println(n.title).

Starter code

Main.kt
object App {
    fun run(): String = "Expert Notes"
}

// add the Note data class (id: Int, title: String)

fun main() {
    // create a Note and print its title
}

Sample solution

Main.kt
object App {
    fun run(): String = "Expert Notes"
}

data class Note(val id: Int, val title: String)

fun main() {
    val n = Note(1, "Merhaba")
    println(n.title)
}

Expected output

Merhaba

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match the Note parts

Term Meaning
data class Note Shared data
val id Identifier
val title Title
commonMain Source set

2 Which source set does the Note class live in?

Main.kt
Shared data lives in commonMain.
  • iosMain
  • commonMain Correct answer
  • jsMain
  • androidMain

Explanation: Note lives in commonMain; every target shares it.

3 Complete the Note definition

Question
data class Note(val id: Int, val ____: String)
Answer
data class Note(val id: Int, val title: String)

Explanation: The Note class carries id and title fields.

All lessons in Expert