PHpullh
학습 라이브러리/Kotlin/KMP (Kotlin Multiplatform) 소개

KOTLIN · 디자인패턴

KMP (Kotlin Multiplatform) 소개

Kotlin Multiplatform(KMP)은 비즈니스 로직을 commonMain에 한 번 작성하고 Android, iOS, Web, Desktop에서 공유합니다. expect/actual 메커니즘으로 플랫폼별 구현을 분리하여 최대한의 코드 재사용을 달성합니다.

디자인패턴고급kmpmultiplatformexpect-actualcross-platform

핵심 설명

Kotlin Multiplatform(KMP)은 비즈니스 로직을 commonMain에 한 번 작성하고 Android, iOS, Web, Desktop에서 공유합니다. expect/actual 메커니즘으로 플랫폼별 구현을 분리하여 최대한의 코드 재사용을 달성합니다.

Kotlin code

// commonMain/kotlin/Platform.kt
// expect 선언: 공통 코드에서 인터페이스 정의
expect fun getPlatformName(): String

expect class HttpClient() {
    suspend fun get(url: String): String
}

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

// androidMain/kotlin/Platform.android.kt
// actual 구현: Android 플랫폼용
actual fun getPlatformName(): String = "Android ${android.os.Build.VERSION.SDK_INT}"

actual class HttpClient actual constructor() {
    actual suspend fun get(url: String): String {
        // OkHttp 사용
        return okhttp3.OkHttpClient().newCall(
            okhttp3.Request.Builder().url(url).build()
        ).execute().body?.string() ?: ""
    }
}

// iosMain/kotlin/Platform.ios.kt
// actual 구현: iOS 플랫폼용
actual fun getPlatformName(): String = "iOS ${UIDevice.currentDevice.systemVersion}"

actual class HttpClient actual constructor() {
    actual suspend fun get(url: String): String {
        // NSURLSession 사용
        return "" // iOS 네이티브 네트워크 호출
    }
}

// 공유 테스트
// commonTest/kotlin/GreetingTest.kt
fun testGreeting() {
    val greeting = Greeting()
    assert(greeting.greet().startsWith("Hello from"))
}

학습 팁

KMP 프로젝트 시작 시 KMP Wizard를 사용하면 프로젝트 구조를 자동 생성할 수 있습니다. Ktor, kotlinx.serialization 등 KMP 호환 라이브러리를 우선 선택하세요.

주의할 점

expect/actual을 남용하면 공통 코드의 이점이 줄어듭니다. 인터페이스와 DI(의존성 주입)를 활용해 플랫폼 의존성을 최소화하세요.

자주 묻는 질문

KMP (Kotlin Multiplatform) 소개란 무엇인가요?

Kotlin Multiplatform(KMP)은 비즈니스 로직을 commonMain 에 한 번 작성하고 Android, iOS, Web, Desktop에서 공유합니다. expect/actual 메커니즘으로 플랫폼별 구현을 분리하여 최대한의 코드 재사용을 달성합니다.

KMP (Kotlin Multiplatform) 소개 학습 시 주의할 점은 무엇인가요?

expect/actual 을 남용하면 공통 코드의 이점이 줄어듭니다. 인터페이스와 DI(의존성 주입)를 활용해 플랫폼 의존성을 최소화하세요.