Multiplatform Kotlih in single directory via #ifdefs


#1

I currently have a multiplatform project working, with directory structure of:

foobar-common/src/main/kotlin/foobar/...
foobar-js/src/main/kotlin/foobar/...
foobar-jvm/src/main/kotlin/foobar/...

I am not a fan of this structure as it requires keeping three file trees synced up and named similarly.

Is there a way instead, to have a single tree, and have

#ifdef JS …
#endif

#ifdef JVM …
#endif

and have all three trees “merged into one” via ifdefs ?

Thanks!


#2

Nop and for good reasons. In any project with multiple people working on it this leads to problems when porting code. Normally not all people write platform specific code for all platforms. That way it is far easier to port a project and to find all the platform specific code.

Try to structure your program in a way where you have only a little bit of platform specific code. In general you want all of your logic and stuff in common and only handle platform specific stuff in js and jvm, etc


#3

The C preprocessor is language independent, so it is possible to use it if you really want to. I still highly recommend that you do not and instead use the structure that you presented above.


#4

I’m not willing to give up all the IntelliJ auto completion / red squiggly type checking for this. Unless IntelliJ also supports the conditional compilation, I’m not ready to switch.


#5

You can do something by implementing custom gradle build script and select files to complile depending on some feature, but in general C preprocessor is one of the worst programming language techniques ever. You can always design your multiplatform project so all overrides are in one file.


#6
  1. Clojure has something similar to ifdefs – cljc:

It has worked out quite well for me for clj -> js/jvm projects.

  1. I don’t think Gradle gets around the issue of breaking IntelliJ syntax checking. Any solution that breaks IntelliJ on-the-fly type checking of Kotlin is too high a cost.