Yao-Wen Mei
07/06/2022, 9:57 PM@Serializable (with = customJavaSerializer.class)
annotation on a Java class? (I want to have both the class itself and the custom serializer defined in Java, but use them in Kotlin)
I have tried define a Java class Hello
, and then define a custom serializer HelloSerializer
in Java. What is the field name or method name (like the Impl
in the previous annotation example) should I give, so that the complier plugin can get access to my custom java serializer with @Serializable
? Thank you very much.ephemient
07/06/2022, 11:10 PMstatic Companion INSTANCE;
and a serializer()
method inside Companion
, but this whole approach looks quite ill-advised to me. what is preventing you from defining the class in Kotlin?Yao-Wen Mei
07/07/2022, 12:53 AM@Serializable
unless 1) I use @Contextual
, 2) Or I find out a way to apply @Serializable
to the Java classes. Do you have any suggestions?ephemient
07/07/2022, 12:54 AMYao-Wen Mei
07/07/2022, 12:56 AMstatic Companion Instance
and serializer()
in my Hello.class
:
@Serializable(with = HelloSerializer.class)
public final class Hello {
public static final Hello.Companion INSTANCE = new Hello.Companion((DefaultConstructorMarker)null);
public static final class Companion {
private Companion() {
}
public Companion(DefaultConstructorMarker $constructor_marker) {
this();
}
@NotNull
public final KSerializer serializer() {
return new HelloSerializer();
}
}
}
And this is my custom serializer:
public final class HelloSerializer implements KSerializer<Hello> {
@Override
public Hello deserialize(@NonNull Decoder decoder) {
return new Hello();
}
@NonNull
@Override
public SerialDescriptor getDescriptor() {
return SerialDescriptorsKt.PrimitiveSerialDescriptor("Hello", (PrimitiveKind) PrimitiveKind.STRING.INSTANCE);
}
@Override
public void serialize(@NonNull Encoder encoder, Hello hello) {
encoder.encodeString("hello");
When I try to get `Hello`’s serializer from Kotlin, I got NoSuchElementException
ephemient
07/07/2022, 12:57 AMINSTANCE
is wrong, it's Companion
- but I don't think this is a good idea anyway, it's possible future compiler plugin versions will require valid Kotlin metadata as well which you can't supplyYao-Wen Mei
07/07/2022, 1:00 AMkotlin-serialization-core
library, but independent from our Kotlin extension library.ephemient
07/07/2022, 1:01 AMYao-Wen Mei
07/07/2022, 1:03 AMINSTANCE
to Companion
, but still the same `NoSuchElementException`🤣.ephemient
07/07/2022, 1:06 AMephemient
07/07/2022, 1:07 AMYao-Wen Mei
07/07/2022, 1:22 AMI don't think it can be guaranteed that you haven't missed anything that it might additionally depend on in the future
Is this plugin supposed to be backward compatible?ephemient
07/07/2022, 1:23 AMKSerializer
will fail when the class loads. you can't do thatYao-Wen Mei
07/07/2022, 1:23 AMephemient
07/07/2022, 1:23 AMYao-Wen Mei
07/07/2022, 1:28 AM