Hello, I'm just starting out on learning how to us...
# serialization
r
Hello, I'm just starting out on learning how to use KotlinX (and serdes in general) and I am running in to an issue I can't seem to understand how to solve. I have a
@Serializable class A
and I have a helper class for companions to automatically grab a file to deserialize something in to an
A
and put it in
A(.Companion).INSTANCE
. However, using
.INSTANCE
gets a bit annoying to use and looks kind of gross, so I am trying to convert
A
in to a
@Serializable sealed interface A
, so that
A.Companion
can be an
A
and I can simply reference
A
rather than
A(.Companion).INSTANCE
. I can't seem to understand enough to get this working with a
sealed interface
, I keep running in to polymorphism errors or NPEs if I try to delegate similar to how I do in
Loader
, so I am here for help. Here's a minimum example.
Copy code
abstract class Loader<T>(val type: StringFormat, val filePath: String, val serializer: () -> KSerializer<T>, ) {
    val INSTANCE by lazy {
        type.decodeFromString(serializer(), File(filePath).readText())
    }
}
current
Copy code
@Serializable
class A(val someProperty: Int) {
    companion object: Loader<A>(
        type = Json.Default, filePath = "./config/A-config.json", serializer = { A.serializer() }
    )
}

fun main() {
    A.INSTANCE.someProperty
}
goal
Copy code
@Serializable
sealed interface A {
    val someProperty: Int
    companion object: Loader<A>(
        type = Json.Default, filePath = "./config/A-config.json", serializer = { A.serializer() }
    )
}

fun main() {
    A.someProperty
}