Reputation: 5271
I have a data class in commonMain (called Person
) that I would like to access from jvmMain as type java.io.Serializable
.
I have a solution, which is shown below, but I was wondering if this is the best approach. I also found that the library kotlinx.serialization exists, but I'm not sure if it can be a solution.
This code works fine, although the required DummyInterface may be a bit useless.
// CommonMain
expect interface Serializable
data class Person(val name: String) : Serializable
// jsMain
interface DummyInterface
actual typealias Serializable = DummyInterface
//jvmMain
actual typealias Serializable = java.io.Serializable
fun main(args: Array<String>) {
val p1: java.io.Serializable = Person("abc")
println(p1)
}
// gradle.kotlin.kts
plugins {
application
kotlin("multiplatform") version "1.4.32"
kotlin("plugin.serialization") version "1.4.32"
}
repositories {
mavenCentral()
}
kotlin {
jvm {
compilations.all {
kotlinOptions.jvmTarget = "11"
}
withJava()
}
js(IR) {
binaries.executable()
browser {}
}
sourceSets {
val commonMain by getting {
dependencies {
implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.1.0")
}
}
val jvmMain by getting {
dependencies {
implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.1.0")
}
}
}
}
// commonMain/kotlin/Person.kt
import kotlinx.serialization.*
@Serializable
data class Person(val name: String)
// jvmMain/kotlin/main.kt
fun main(args: Array<String>) {
// Fails with: "Type mismatch: inferred type is Person but Serializable was expected"
val p1: java.io.Serializable = Person("abc")
println(p1)
}
I know why it fails with a type mismatch, but I would hoping that the kotlinx.serialization plugin would magically add the interface java.io.Serializable to the Person data class.
Upvotes: 3
Views: 2858
Reputation: 7602
kotlinx.serialization
wasn't exactly developed as an java.io.Serializable
abstraction or something. It's a purely kotlin serialization library, for serializing/deserializing JSON
objects.
Yes, your first approach is a proper solution I'd say.
There is a similar implementation for Parcelize
, you could check out moko-parcelize, it's doing the same thing.
Upvotes: 4