Kotlin Multiplatform question: I want to have a cl...
# getting-started
a
Kotlin Multiplatform question: I want to have a class in commonMain for decoding strings, and a JVM specific implementation that has overloaded functions for handling InputStreams. I can do an expect/actual class, but the
expect class
can't have function bodies. So I'd need to create a common class for the shared functions and re-use it in each `actual class`:
Copy code
// commonMain
expect class MyDecoder {
  fun decode(string: String): Node // bodies are not allowed :(
}

internal class MyDecoderCommon {
  fun decode(string: String): Node { /* impl*/ }
}

// jvmMain
actual class MyDecoder {
  private val common = MyDecoderCommon()
  fun decode(string: String): Node = common.decode(string)
  fun decode(inputStream: InputStream): Node = decode(inputStream.toString())
}
Is this the best pattern available at the moment? I'm not a fan because I get dinged with a 'expect/actual classes are in beta' warning, and it's a bit duplicated. (Making
MyDecoder
a regular class and adding extension functions in jvmMain, like
fun MyDecoder.decode(inputStream: InputStream): Node
are also an option - however I want to support Java users)
o
Two thoughts: 1. When worrying about the Beta state of expect/actual classes, you might want to look at the roadmap to stability. 2. Would
open class MyDecoder
(with implementation) in
commonMain
plus
class MyJvmDecoder : MyDecoder
in
jvmMain
work for you? (Because with the extra
decode
overload it really is a derivative, not the same thing as
MyDecoder
).
thank you color 1
m
For what you showed as the implementation of
fun decode(InputStream)
I would just make that an extension function.
a
@Michael Krussel I mentioned extension functions in my message :) Normally I would use them, but in this case, I want to provide a good API for Java users, and extension functions aren't as convenient for them.
m
using
@fileJvmName
to give a good name to the class containing the extension functions would create a natural class of static functions for your Java users. Not quite as good extension functions, but it is the normal Java way of doing it. But other wise I think what you did is a fine implementation. I've done similar with just internal functions that I expect most of the actual classes to use.