Search code examples
kotlinkotlin-interopkotlin-native

Can anyone here explain the Kotlin/Native spinner app project structure in detail? Also the specifics on how different modules work


I would like to specifically know how the common module is used by the individual client modules. Which are the truly common parts that is shared by all the clients and the server.

Thank you.


Solution

  • This is easy. I suspect you're talking about Kotlin multiplatform modules.
    Consider print and println.

    In the common module we can expect a print function:

    expect fun print(a: String)
    

    But we don't know how was it implemented, because the common module doesn't know anything about Java's System.out, as well as JavaScript's console.
    But the common module can expect such function that prints a String on screen, without providing an implementation.

    Since we have print, we can implement println:

    fun println(a: String) = print("$a\n")
    

    All codes above are inside the common module.
    And all you have to do is to to implement print for JVM/JS spererately.

    For JVM:

    actual fun print(a: String) = System.out.println(a)
    

    For JS:

    actual fun print(a: String) = console.log(a)
    

    (Maybe) For Native:

    actual fun print(a: String) = printf(a)
    

    The three code blocks above are inside client modules.

    Consider you've designed a data format, you have encoding and decoding code. Those codes are used in your Android device (JVM), your backend server (JVM), your frontend webpage (JS), your native app (Native).
    You use Kotlin in all those sub projects but you want to write the encoder/decoder only once. Kotlin multiplatform module solves this probelm.

    About the spinner app

    It's not using the standard kotlin approach for creating multiplatform project. It's a trick on gradle.
    There's a readResources (and randomInit as well, for osx/linux) function that implements differently on platforms but of the same signature, and gradle will decide which Kommon.kt should be compiled with the client projects.

    readResources and randomInit should be marked as actual, and there should be a "common module" that has "expect"ed those two functions.
    They didn't do this probably because Kotlin 1.2 (which brings stable multiplatform support) isn't out when KotlinConf holds.