Kotlin Help

Add dependencies to your project

You've already created your first cross-platform Kotlin Multiplatform Mobile project! Now let's learn how to add dependencies to third-party libraries, which is necessary for building successful cross-platform applications.

Dependency types

There are two types of dependencies that you can use in Multiplatform Mobile projects:

  • Multiplatform dependencies. These are multiplatform libraries that support multiple targets and can be used in the common source set, commonMain.

    Many modern Android libraries already have multiplatform support, like Koin, Appolo, and Okio.

  • Native dependencies. These are regular libraries from relevant ecosystems. You usually work with them in native iOS projects using CocoaPods or another dependency manager and in Android projects using Gradle.

When you work with a shared module, you can also depend on native dependencies and use them in the native source sets, androidMain and iosMain. Typically, you'll need these dependencies when you want to work with platform APIs, for example security storage, and there is common logic.

For both types of dependencies, you can use local and external repositories.

Add a multiplatform dependency

Let's now go back to the app and make the greeting a little more festive. In addition to the device information, add a function to display the number of days left until New Year's Day. The kotlinx-datetime library, which has full multiplatform support, is the most convenient way to work with dates in your shared code.

  1. Navigate to the build.gradle.kts file in the shared directory.

  2. Add the following dependency to the commonMain source set dependencies:

    kotlin { sourceSets { val commonMain by getting { dependencies { implementation("org.jetbrains.kotlinx:kotlinx-datetime:0.3.3") } } } }
  3. In shared/src/commonMain/kotlin, create a new file NewYear.kt and update it with a short function that calculates the number of days from today until the new year using the date-time date arithmetic:

    import kotlinx.datetime.* fun daysUntilNewYear(): Int { val today = Clock.System.todayAt(TimeZone.currentSystemDefault()) val closestNewYear = LocalDate(today.year + 1, 1, 1) return today.daysUntil(closestNewYear) }
  4. In Greeting.kt, update the greeting() function to see the result:

    class Greeting { fun greeting(): String { return "Guess what it is! > ${Platform().platform.reversed()}!" + "\nThere are only ${daysUntilNewYear()} left until New Year! 🎅🏼 " } }
  5. Run the updated application on Android and iOS and see the results:

Updated mobile multiplatform app with external dependencies

Next step

Add more dependencies and more complex logic to your project.

See also

Get help

Last modified: 02 August 2022