PHpullh
학습 라이브러리/Kotlin/멀티플랫폼 타입 (Kotlin Multiplatform)

KOTLIN · 기초 문법

멀티플랫폼 타입 (Kotlin Multiplatform)

Kotlin Multiplatform에서 expect/actual 선언으로 플랫폼별 구현을 분리합니다.

기초 문법고급multiplatformexpectactualkmp

핵심 설명

Kotlin Multiplatform에서 expect/actual 선언으로 플랫폼별 구현을 분리합니다.

Kotlin code

// commonMain - 공통 코드
expect fun platformName(): String
expect class UUID {
    fun asString(): String
}

// 공통 비즈니스 로직
fun greet(): String {
    return "Hello from ${platformName()}!"
}

// jvmMain - JVM 구현
actual fun platformName(): String = "JVM"
actual class UUID(private val value: java.util.UUID) {
    actual fun asString(): String = value.toString()
}

// 사용 예시 (공통)
fun main() {
    println(greet())
    println("플랫폼: ${platformName()}")
}

학습 팁

공통 모듈에 최대한 많은 비즈니스 로직을 작성하고, 플랫폼별 모듈은 I/O나 UI 등 플랫폼 특화 기능만 구현하세요.

주의할 점

expect 선언에 대응하는 actual이 모든 타겟 플랫폼에 있어야 합니다. 누락하면 컴파일 오류가 발생합니다.

자주 묻는 질문

멀티플랫폼 타입 (Kotlin Multiplatform)란 무엇인가요?

Kotlin Multiplatform에서 expect / actual 선언으로 플랫폼별 구현을 분리합니다.

멀티플랫폼 타입 (Kotlin Multiplatform) 학습 시 주의할 점은 무엇인가요?

expect 선언에 대응하는 actual 이 모든 타겟 플랫폼에 있어야 합니다. 누락하면 컴파일 오류가 발생합니다.