RayeW47
08/31/2022, 9:05 PM@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.
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
@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
@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
}