Thread
#multiplatform
    archana 0623

    archana 0623

    1 year ago
    Hello, I have recently been checking code sharing in KMM and have a question like how to know when to use expect and actual fun in common module KMM and when not to use it, like with some example usecase
    s

    Sam

    1 year ago
    Expect/actual is useful for bridging common code to a platform. Most of the time an interface is a better option. However if the common code needs to do the instantiation, expect/actual is better to use. Kotlin.Random in the std library is a good example of expect/actual. It wraps or type aliases the platform random number generator. One could certainly use an interface and pass in an RNG to a class or function as a dependency but the code may be cleaner in this case if the common code can create its own.
    John O'Reilly

    John O'Reilly

    1 year ago
    Another good example if you're using SQL Delight is the creation of DB driver
    archana 0623

    archana 0623

    1 year ago
    Thanks for the examples. Just want to confirm one thing like how do you get to decide that this logic should go into specific modules and this logic I would use interface(expect) and add implementations(actual) and keep them in common module, is it like only for UI/view layer I would keep in the specific module and for rest all other logical part or any other layer I would use expect and actual(which cannot work with one single impl)?
    s

    Sam

    1 year ago
    I default to interfaces because it makes unit testing easier. If the code gets too messy using an interface, I switch to an expect/actual class or function. My opinion is that expect/actual is useful but should be one of the least used options.