CodexBloom - Programming Q&A Platform

Kotlin Multiplatform: implementing Shared Code Accessing Platform-Specific APIs

👀 Views: 1432 💬 Answers: 1 📅 Created: 2025-06-14
kotlin multiplatform dependency-injection Kotlin

I'm getting frustrated with I've been researching this but I'm working on a personal project and I'm sure I'm missing something obvious here, but I tried several approaches but none seem to work... I'm working on a Kotlin Multiplatform project where I have shared code intended to access platform-specific APIs. The goal is to have a common module for business logic while delegating to platform-specific implementations for things like networking and database access. However, I’m running into issues when trying to access a platform-specific function from my shared code. I’ve defined an interface in the shared module: ```kotlin interface PlatformService { fun fetchData(): String } ``` In my Android module, I have a class that implements this interface: ```kotlin class AndroidPlatformService : PlatformService { override fun fetchData(): String { // Accessing Android-specific features return "Data from Android" } } ``` I am then using this service in my shared code like this: ```kotlin class DataManager(private val platformService: PlatformService) { fun getData(): String { return platformService.fetchData() } } ``` However, when I try to instantiate `DataManager` in my Android app, I get a `java.lang.IllegalArgumentException: No implementation found for PlatformService` behavior. I’ve ensured that the dependency injection is set up correctly, but it seems like the shared module is not aware of the Android implementation. I have tried using Koin for dependency injection and I registered the service like this: ```kotlin startKoin { modules(module { single<PlatformService> { AndroidPlatformService() } }) } ``` Despite this, the behavior still occurs. I suspect it might be related to how I’m setting up the Koin module or the visibility of the classes across modules. Any insights into how I can resolve this scenario and ensure that my shared code can correctly access the platform-specific implementation? This is part of a larger web app I'm building. Could someone point me to the right documentation? For context: I'm using Kotlin on Ubuntu 20.04. What am I doing wrong? What would be the recommended way to handle this?