Reputation: 189
Hello StackOverflow community,
I am trying to build a library in Kotlin. I want to have a constant public API surface with multiple implementations for different libraries and a shared codebase, which should also contain Kotlin/JVM code. The public API surface can then be used in other projects and the implementation is selected at runtime (via the classpath).
For example, let's say I want to write a library that I use for storing data on a server. The public API surface looks should have a method like below, but it should also handle the shared business logic like validating the data.
fun storeData(data: String) {
if (data.isNotEmpty()) {
actuallyStoreData(any)
} else {
throw IllegalArgumentException("data cannot be empty");
}
}
private fun actuallyStoreData(data: String) // this method should depend on the implementation
Then I want to implement this library for two different databases: let's say MongoDB and MySQL. So in my project that uses this library, I only access the public API. When the project runs, the implementation of this function should depend on whether my-library-mysql.jar or my-library-mongodb.jar is in the classpath.
Maybe this is a weird thing to ask and I probably think way too complicated, but it would really make the development of my project easier. I tried Kotlin Multiplatform but it doesn't provide the ability to specify a common JVM target. So, is there a way to implement this?
Upvotes: 0
Views: 187
Reputation: 7632
IMO if you're targeting only JVM you may be better of with abstracting away the functionality in an interface.
Kotlin Multiplatform's expect/actual
mechanism is more for abstracting away implementations from different targets (JVM, Native, JS)
Upvotes: 2