Groo

Kotlin Multiplatform 의존성 추가하기 본문

Kotlin Multiplatform

Kotlin Multiplatform 의존성 추가하기

김주엽 2024. 1. 20. 17:12

의존성 종류

1. Multiplatform dependencies

- 여러 플랫폼을 지원하는 멀티 플랫폼 라이브러리

- 보통 여러 플랫폼에서 공통으로 사용하는 commonMain 모듈에 멀티 플랫폼 라이브러리를 추가해서 사용함

- Koin, Apollo, Okio 등이 존재함

 

2. Native Depdencies

- 특정 플랫폼에 한정된 라이브러리

- 보통 각 플랫폼별 고유 api가 해당함

- 예를 들어 내부 스토리지 접근, OS 자체 기능 활용 등


이전 프로젝트에서 이어서 진행할게요.

이번에는 kotlinx-datetime 라이브러리를 사용해서 현재를 기준으로 내년까지 며칠이 남았는지를 보여주는 기능을 구현해 볼게요.

 

 

 

kotlin {
    sourceSets {
        val commonMain by getting {
            dependencies {
                implementation("org.jetbrains.kotlinx:kotlinx-datetime:0.4.0")
            }
        }
    }
}

먼저 shared 모듈의 build.gradle.kts 파일을 열고 commonMain 모듈에 kotlinx-datetime 라이브러리를 추가해 주세요.

import kotlinx.datetime.*

fun daysUntilNewYear(): Int {
    val today = Clock.System.todayIn(TimeZone.currentSystemDefault())
    val closestNewYear = LocalDate(today.year + 1, 1, 1)
    return today.daysUntil(closestNewYear)
}

fun daysPhrase(): String = "There are only ${daysUntilNewYear()} days left until New Year! 🎆"

그리고 commonMain 모듈 내에 NewYear.kt라는 신규 파일을 만들고 kotlinx-datetime 라이브러리를 사용해서 현재를 기준으로 내년까지 며칠이 남았는지 계산하는 로직을 작성해 주세요.

class Greeting {
    private val platform: Platform = getPlatform()

    fun greet(): List<String> = buildList {
        add(if (Random.nextBoolean()) "Hi!" else "Hello!")
        add("Guess what it is! > ${platform.name.reversed()}!")
        add(daysPhrase())
    }
}

마지막으로 기존 Greeting.kt 파일 내 greet 메서드에서 dayPhrase 메서드를 호출하면 끝!


글 작성 시 참고한 문서

샘플 코드

 

 

juyeop03 - Overview

juyeop03 has 24 repositories available. Follow their code on GitHub.

github.com

Comments