reactormonk
10/18/2024, 8:07 AMfun Serializable.toJson(): String = Json.encodeToString(this)
This doesn't seem to match my type I marked as @Serializable
🤔Riccardo Lippolis
10/18/2024, 8:10 AMApplying Serializable to the Kotlin class instructs the serialization plugin to automatically generate implementation of KSerializer for the current class, that can be used to serialize and deserialize the class.which is different from extending the
Serializable
interface 🙂Joffrey
10/18/2024, 8:10 AM@Serializable
is different from the Serializable
interfacereactormonk
10/18/2024, 8:10 AMJoffrey
10/18/2024, 8:11 AMreactormonk
10/18/2024, 8:13 AMJoffrey
10/18/2024, 8:26 AMreactormonk
10/18/2024, 8:27 AMJoffrey
10/18/2024, 8:28 AMreactormonk
10/18/2024, 8:29 AMJoffrey
10/18/2024, 8:29 AMencodeToX
, AFAIKreactormonk
10/18/2024, 8:29 AMJoffrey
10/18/2024, 8:30 AMKxSerializable
interface or somethingJoffrey
10/18/2024, 8:31 AM@Serializable
reactormonk
10/18/2024, 8:32 AMJoffrey
10/18/2024, 8:32 AMreactormonk
10/18/2024, 8:32 AM@Serializable
Joffrey
10/18/2024, 8:33 AMreactormonk
10/18/2024, 8:33 AMJoffrey
10/18/2024, 8:34 AMreactormonk
10/18/2024, 8:34 AM@Serializable
, but ain't much more than thatreactormonk
10/18/2024, 8:34 AMJoffrey
10/18/2024, 8:38 AMreactormonk
10/18/2024, 8:40 AMencodeX
has @Serializable
, although that's probably quite some ksp magicJoffrey
10/18/2024, 8:42 AMreactormonk
10/18/2024, 8:43 AMksp
access the type-checked tree?reactormonk
10/18/2024, 8:43 AMJoffrey
10/18/2024, 8:46 AM@Serializable
alone:
fun myCustomEncode(thing: Any) {
Json.encodeToString(thing)
}
How do you want to check that this is called only with instances of classes marked @Serializable
? Calls to this function could be in different modules, even.
If you use an interface, you can enforce:
// in your core utils
fun MySerializable.toJson(): String = Json.encodeToString(this)
// anywhere in your business code
fun myFunThatEncodes(thing: Any) {
thing.toJson() // type error: expected MySerializable but got Any
}
Joffrey
10/18/2024, 8:47 AM@Serializable
and that can be done by a reflection test or by KSP, whichever you preferreactormonk
10/18/2024, 9:02 AM