https://kotlinlang.org logo
#multiplatform
Title
# multiplatform
a

archana 0623

04/02/2021, 11:38 AM
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

04/02/2021, 12:21 PM
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.
j

John O'Reilly

04/02/2021, 12:22 PM
Another good example if you're using SQL Delight is the creation of DB driver
a

archana 0623

04/02/2021, 12:30 PM
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

04/02/2021, 2:46 PM
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.
1
🙏 1
4 Views