I am trying to build a KMP library. The library us...
# multiplatform
t
I am trying to build a KMP library. The library uses very a specific random sampling algorithm as well as specific PRNG not available in general Java/Kotlin nor Swift standard libraries. Implementations already exist in Java and Swift, and I’d like to reuse those for my KMP library. It was easy to use the Java one; for Swift I initially thought I’d be just as easy but now I’m not so sure. Is there a way to delegate the implementation of an interface defined in common code to Swift code? If so, are there examples?
j
Is the Swift code compatible with Objective-C? Does it have the
@objc
attribute marking the public API?
t
No I don’t think it has. Or at least not in the source file (would that be somewhere else?)
j
If it did have
@objc
, you could use Objective-C interop to add the library and generate Kotlin bindings to call from your Apple native source sets. Then use `expect`/`actual` to make a common API that is implemented with platform libraries.
p
in which case, you’ll need to implement an
@objc
wrapper class, and create the appropriate headers in order to build the bindings for the the swift-only API
j
Alternatively, you can create a Kotlin interface that you can then implement in Swift and inject your implementation into your library at runtime.
at least not in the source file (would that be somewhere else?)
It would be in the Swift source files, yes, above the function definitions.
👍 1
t
Ok looking into this. And what does the “inject at runtime” workflow look like? I haven’t seen that in the docs, but that might be a good way to make a proof of concept work.
j
Use a dependency injection pattern. Your Swift code will have your Kotlin library dependencies, including the interface you want to implement in Swift. Create a Swift implementation. Then there's the Kotlin code that uses that interface's implementation, which will expect an implementation to be passed to its constructor(s). When your Swift code constructs this part of the library's API, it passes its implementation to the constructors. Alternatively, you could use a DI framework, like Koin, to manage the dependencies and inject constructors.
t
Oh I see ok awesome. You’re giving me stuff to chew on for sure. That might work well for a test app I’m building (something unrelated to the question I was asking here but for which you sort of answered one of my issues maybe). As for the library I’ll need to dig in a bit more; the @objc wrapper class idea might work well there. Thanks a BUNCH! This is the sort of stuff I needed to hear/read. ❤️
👍 1