Is there a Kotlin Multiplatform–friendly abstracti...
# multiplatform
m
Is there a Kotlin Multiplatform–friendly abstraction for Android’s
Context
that can be used in
commonMain
rather than directly referencing
android.content.Context
?
Like if I defined an abstract Context interface in my Common Main:
Copy code
// Abstract context for shared code
interface SharedContext

// The common interface
interface MyComposableHandler {
    fun doSomething(context: SharedContext)
}
Then casted in my Android source set:
Copy code
// Android implementation of the interface
class AndroidComposableHandler : MyComposableHandler {
    override fun doSomething(context: SharedContext) {
        val activity = (context as? AndroidSharedContext)?.activity
w
What are you trying to achieve? Usually you either inject Context into the Android variant of your expected class or directly reference LocslContext (or I guess LocalActivity given your snippet) as part of the composable implementation.
e
Seconded. Why do you need a Context object specifically? In my experience I’ve never actually needed one, just needed a “service” that can be grabbed via context on android so that I have that service type in common and on android, resolving that service is done with the context
p
I do think, overall commonizing the Activity/Context or LocalActivity/LocalContext is not a bad idea/strategy, with the purpose of attracting Android devs to CMP. The challenge is that Context or Activity are huge classes. In this sense as suggested above, it is better to abstract just the functionality you need out of it. Eg, if you need a context to get Strings, better abstract a StringResolver, if you need certain service, better abstract the SpecificServiceFactory on each target.
👍 1
m
Well I feel like there’s been a few occasions when I’ve needed it outside of a scope of a Composable
I must be going about it wrong
In this case I have registered the context with koin
androidContext(this@MyApplication)
Another related is the Android Stripe SDK requiring
ComponentActivity
to initialise the `PaymentSheet`: https://kotlinlang.slack.com/archives/C3PQML5NU/p1763450494383769?thread_ts=1738603708.469789&cid=C3PQML5NU
m
Use expect/actual with: commonMain:
expect class PlatformContext
androidMain (no casting required):
actual typealias PlatformContext = android.content.Context
iosMain:
actual class PlatformContext
? I use this approach for
PlatformTypeface
because compose font classes don’t expose
hasGlyph
functionality whereas platform-specific typeface classes do.
❤️ 1
m
The following declaration is incompatible because modality is different. Expect declaration modality is ‘final’. Actual declaration modality is ‘abstract’:
expect class PlatformContext : Any
ah needed to be:
Copy code
expect abstract class PlatformContext
m
I forgot to mention I added
@Suppress("EXPECT_ACTUAL_CLASSIFIERS_ARE_IN_BETA_WARNING")
Perhaps also the fact that android
Typeface
is a concrete class also matters, not sure.
👍 1
m