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

Shawn Witte

09/26/2020, 4:47 AM
Hello everyone. I've been playing with multiplatform a bit and I'm wondering if anyone has some insight on the pros/cons of using
expect/actual
vs using an interface. I'm especially curious if there are use cases for
expect/actual
that can't be solved with an interface or are obviously better suited to the
expect/actual
pattern. I asked a question on the forums, but it didn't get any traction.
i

ian.shaun.thomas

09/26/2020, 4:52 AM
From my experience, you should only use expect/actual for concrete implementations and thus they be should be rare. Interfaces are definitely what I lean on the most.
s

Sam

09/26/2020, 3:42 PM
If you need to instantiate the class from common code then expect/actual will help make that cleaner. To create platform instances from common code without expect/actual would be ugly. You would need some sort of factory class passed into your common code everywhere. The two can definitely be used together. In one project I had a repository interface declared, mostly as a testing seam. Then I had an Android and iOS implementation that wrote data to the file systems of each platform. The class calling that code took the repo as a constructor parameter with a default value set as the file based repo class.
s

Shawn Witte

09/26/2020, 9:03 PM
As a more concrete example: input. The current (early/prototyping) state of my app uses numbered menus printed to the console and takes numeric input from the user to make a selection. The options I see for obtaining the input (platform-dependent): 1. Create a top-level
expect fun getNumericInput(): Int
or
expect class MenuIO
where I keep all the necessary IO functions 2. Create an
interface MenuIO
that I implement and inject from the platform-level entry points. It seems to me that the general rule you're both getting at could be stated "interfaces for injectables and expect/actual for newables" (assuming the injectable/newable dichotomy)
7 Views