I have added a Kotlin library which contained a class like
@Serializable data class Dog(@SerialName("age")val age: Int);
I tried to put it as an intent extra like
intent.putExtra("data", d); //d is an instance of Dog
but the IDE showed no such argument overload error. I also tried manually converting like
intent.putExtra("data", d as java.io.Serializable);
but the IDE said "The cast can never succeed". I wondered if @Serializable
is a different thing from java.io.Serializable
, but it was the same thing:
internal actual typealias Serializable = java.io.Serializable
So, why can't I put that class instance as an extra?
This behavior is indeed pretty disappointing, crazy that we can't use the new kotlinx Serialization with Intent extras.
The best workaround I've seen up to this point is to use Json.encodeToString(value)
to manually serialize your object. Then, store the string with intent.putExtra("some_key", valueString)
.
To get the value out of the Intent later, get the value Json String from the Intent as usual: intent.getStringExtra("some_key")
.
Then, use Json.decodeFromString(valueString)
to obtain the original value.