JetBrains / compose-multiplatform

Compose Multiplatform, a modern UI framework for Kotlin that makes building performant and beautiful user interfaces easy and enjoyable.
https://jetbrains.com/lp/compose-multiplatform
Apache License 2.0
16.17k stars 1.17k forks source link

How to have different implementations for Linux and Windows? #4453

Closed mahozad closed 7 months ago

mahozad commented 7 months ago

How to provide an expect and separate actuals for Linux and Windows?

Because something should be implemented differently depending on the OS.

ryanmitchener commented 7 months ago

@mahozad I would recommend reading through https://kotlinlang.org/docs/multiplatform-hierarchy.html#default-hierarchy-template. You can set up your folder structure to have some target specific code via expect/actual. For windows and linux you would need to use the mingw and linux directories

mahozad commented 7 months ago

Are you sure? I think it's for native targets not jvm targets. Is there any compose multiplatform example?

m-sasha commented 7 months ago

There are no separate source sets for JVM on Windows/Linux/macOS; you just switch (at runtime) on the OS. You can use org.jetbrains.skiko.hostOs, or any 3rd-party OS-detecting library in Java.

ryanmitchener commented 7 months ago

@mahozad Sorry, I didn't realize you were trying to do this on the JVM. In that case what m-sasha said is true. There are no separate source sets for JVM targets. Instead, use the org.jetbrains.skiko.hostOs and either perform the OS check in-line or use it in your DI to inject the appropriate implementation based on OS.

igordmn commented 7 months ago

Yes, checking it in runtime is the default way.

If you need different binaries with different code, you can separate your project by different source sets, and include different sources depending on hostOs inside build.gradle.kts in build-time.

If your project is kotlin("multiplatform"), you can define an additional sourceset this way:

kotlin {
  sourcSets {
    if (...) { // check if it is Windows
        val windowsDesktopMain by creating {
            dependsOn(desktopMain)
        }
    }
    ...
  }
  ...
mahozad commented 7 months ago

The above solution by igordmn does not work even though I provided actual declaration in windowsDektopMain source set (with and without applyDefaultHierarchyTemplate() ):

Expected property 'myVariable' has no actual declaration in module <MyApp> for JVM
okushnikov commented 2 months ago

Please check the following ticket on YouTrack for follow-ups to this issue. GitHub issues will be closed in the coming weeks.