What advantage or solution to specific edge case, ...
# kotlin-native
p
What advantage or solution to specific edge case, the
actual/expect
feature has over regular interface/abstract class design. Perhaps not having to write down the interface 🤔
a
One way to use jvm classes or other platform types as alias targets without explicit declarations in jvm code. Only define stub in common code
Maybe some other cases where you don’t want to abstract the whole class or type into an interface like functions
p
Got it, sweet
a
But otherwise I don’t see a strong benefit if anything it’s more restrictive to what you can contain
p
I have been playing with a compose desktop/android project and haven't had the need to use it. But I see it all around in MPP samples.
a
It’s probably a useful feature and unique to know when working in mpp . And “nifty”
It’s compiler enforced DI for platform implementations in my opinion
p
That's another angle to see it. Guaranteeing all platforms implement the stub
n
Very useful for sharing logic across platforms. Especially if one wants to share logic with some platforms, and not others. An example of this is sharing logic for desktop platforms (Linux, Windows, Mac OS etc) only.
One increasing use of expect/actual is sharing logic that uses symbols from a C library via the experimental C Commonizer (part of Kotlin Native). Many C libraries provide an API that is the same across many different platforms.
k
We generally say use interfaces unless you can’t, which is a gross oversimplification, but that’s the guideline. I find a lot of KMP tutorials, and a lot of new users, assume they’ll use expect/actual a lot, but you really don’t. One common exception I have is factory functions. An expect function is useful if you want a default implementation in common easily (but this is more common in the case of libraries). There are other cases where expect classes make more sense, but I’ve found it difficult to nail down clear use cases for regular “apps”. Mapping to native code can be a different story, depending.
Interfaces are more flexible, but you need more setup to get an instance (which is where the factory function comes in)
p
Thanks Kevin