I’m trying to create a `common` API that is simila...
# multiplatform
s
I’m trying to create a
common
API that is similar in Java and JS. It involves a tree of content, and each node is exposed through the common API. It’d be nice if I didn’t have to allocate an extra class for each node to properly delegate to each platform (since the trees can be rather large). Touchlab showed off an interesting approach a few years ago using expect / actual type aliases with extension properties. This doesn’t work in my case because some of the classes in JS aren’t open, or some are interfaces in Java, and classes in JS. I’m interested if there are any other creative solutions to this that I haven’t thought of.
b
Expect interfaces in common and then when implementing actuals as class typealias suppress type error with one if these https://github.com/JetBrains/kotlin/blob/master/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/rendering/DefaultErrorMessages.java#L70
After that roll out your extension functions
Kotlin stdlib uses this a lot
Just be careful not to forget actuals in all platforms as you'll be losing compile safety
s
This would work in JS obviously. This works in JVM too?
b
Yes, I've used it myself already
s
Let me give it a shot
b
Obviously you'll need some form of builder functions to construct the instances from common
s
so do you have an example?
Copy code
expect interface HtmlElement
I’m not seeing a way to circumvent the error in the actual
Those suppressions are intentionally not suggested by the ide
s
oh wow - Thankyou, I think I see what’s happening now. You are basically telling the compiler on the
expect
not to check for `actual`s, and then you tell the `actual`s not to check for `expect`s. You break the relationship from the compilers perspective, but the result is you can do what you need to in each platform without object allocations. This is painful. There should be a better user story from a multiplatform perspective to solve this. Thank you for showing me this though!
It does seem to work though.
b
Yeah, ideally we should be able to
expect type XXX
which then can be any kind of type (class, interface, union?)
Basically anything you could put in as a generic arg constraint