CodeBlanks Logo Icon CodeBlanks

commonMain

Learn shared code with commonMain.

What is commonMain?

commonMain is the source set in KMP that holds shared code. Code written here can be used by every target.

Inside commonMain you may use the Kotlin stdlib, data classes, functions and expect declarations. Platform-specific APIs (iOS frameworks, JVM classes) cannot be used here. Instead you write a contract with expect, and each target implements it with actual. This keeps shared logic in one place.

commonMain dependencies

Dependencies for commonMain are added in Gradle with a commonMain { dependencies { ... } } block. Libraries added here are shared by every target.

For instance the Ktor client, kotlinx.coroutines or kotlinx.serialization can be added in commonMain. Platform libraries go into the matching target source set. This split keeps shared logic clean. Only multiplatform-compatible libraries may be used in commonMain.

Practice Write commonGreet

Define fun commonGreet(): String. It should return "Hello from commonMain". In main, write println(commonGreet()).

Starter code

Main.kt
// add the commonGreet function

fun main() {
    // print the commonMain greeting
}

Sample solution

Main.kt
fun commonGreet(): String = "Hello from commonMain"
fun main() {
    println(commonGreet())
}

Expected output

Hello from commonMain

Questions and answers

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

1 Complete the expect declaration

Question
____ fun platformName(): String
Answer
expect fun platformName(): String

Explanation: expect declares a contract in commonMain.

2 Match the commonMain parts

Term Meaning
commonMain Shared source set
expect Contract
actual Implementation
kotlinx.coroutines Shared library

3 What is the role of the commonMain source set?

Main.kt
commonMain is the hub of sharing.
  • Write platform code
  • Freeze classes
  • Write tests
  • Hold shared code Correct answer

Explanation: commonMain holds shared code; platform code goes into target source sets.

All lessons in Expert