As Serialization work with annotation @Serializable
How do you defined a method that should receive Serializable class or a generic constraints ? with java.io.Serializable ?
I’d use Any. And put a comment stating that the object should be serializable.
By the way what’s your use-case?
Being annotated with @Serializable doesn’t mean much for a class. It mean that you can try to serialize its instances (but possibly fail), is there a reason you can’t take the object after it has been serialized?
Java serialization does not have anything to do with kotlin serialization. They are completely orthogonal and work in different ways. Kotlin serialization works on compile-time serializer generation so there is no special interface for it.
@Serializable is a good idea, but I don’t think that it’s productive to link it to kotlinx-serialization. You would better have it a standard core annotation that would, at compile-time:
make (or require that) classes and interfaces implement java.io.Serializable for jvm targets
declare abstract streaming virtual operators (for instance) for LLVM targets
If you want to ensure at compile time that the value is serializable with Kotlin Serialization, then you have to explicitly take the serialization strategy.
Notice the two overloads of Json.encodeToString. One will only tell you at runtime if the class is not serializable because it dynamically looks for the serializer (and might fail). The other takes the serializer explicitly so there’s no way for it to be missing at runtime.
You’ll need to model you method signatures like this to ensure compile time checking:
fun <T> doSomeSerializing(serializer: SerializationStrategy<T>, value: T)
And you’ll need to provide the serializer when calling:
That’s instructive. But we may not be speaking about the same thing. I’m searching for a way to express in multiplatform kotlin that when targeting a jvm platform, a class/interface will implement or is required to implement java.io.Serializable.
@Wasabi375 Yes of course, that’s what I meant. My point was to make it part of the core, and maybe add other behaviors for other platforms. kotlinx-serialization is a much higher level library (and could make use of it, detecting right away more non serialization issues at compile time).