Is there a way to check @Serializable annotation a...
# serialization
u
Is there a way to check @Serializable annotation at compile time? I'm getting burned at runtime and that's often too late
j
It would be best to have tests regardless (so it is always tested that the server output can be processed correctly in your app). This would also require the
@Serializable
annotation on the correct classes.
Copy code
fun TestCorrectlyParsedJsonForClass_SomeClassName() {
    assertEquals(Json.decode("""
        { 
            "SomeExampleJson": "that is formatted correctly",
            "name": "Hello"
        }
    """), SomeExampleJson(name="Hello")
If you don't want to write your own tests, I think there is no functionality built-in the gradle plugin to ensure that every class is annotated correctly, that would be quite a bit of work imo. Personal recommendation: stick to the tests, they might save you at some point.
u
I'd argue this should be a compiler job, same as you dont test nonnull vals for null maybe a lint check that can crawl every Json.encode/decode callsite and see if it has the annotation?
If I can forget to add the annotation, I can forget to add the test as well
j
Well the problem here is that you could be using a Kotlinx.serialization converter for retrofit, for example So you would use the class in retrofit, and the converter itself could only notice at runtime that there is a
.serializer()
missing for that class
u
Yea :/ Maybe explicitly check retrofit return types?
v
Use a linter rule that forbids reflection based serialization calls, then you need to call
.serializer()
explicitly and that will fail compilation?
u
hmm reflection? I thought it was all compile time generated
v
It is. But there are variants of the "serialize this" and "deserialize this" methods that use reflection to get hold of the compile time generated serializer. And if those do not find the serializer method, it means the type is not annotated or the compiler plugin was not applied. If you use the versions where you give the serializer explicitly, you need to call that method manually and thus will get a compile time error.
Or how do your calls look like?