Devabc
Devabc

Reputation: 5271

Kotlin commonMain with java.io.Serializable

Problem

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.

Current code and solution: expected and actual types

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)
}

Tried and failed code with kotlinx.serialization

// 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.

Question

  1. Is solution with expected and actual types, the best solution for this problem?
  2. Would kotlinx.serialization also be able to provide a solution? If so, what code should I alter?

Upvotes: 3

Views: 2858

Answers (1)

R&#243;bert Nagy
R&#243;bert Nagy

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

Related Questions