It’s possible to define such types as Drawables and String Resources this way:
@DrawableRes val d:Int
@StringRes val s:Int
How it’s possible to define type for @Serializable
without adding extra interface to all its classes?
It’s possible to define such types as Drawables and String Resources this way:
@DrawableRes val d:Int
@StringRes val s:Int
How it’s possible to define type for @Serializable
without adding extra interface to all its classes?
I’m not really sure what do you ask. Could you rephrase the question or provide a full code example that concerns you? BTW, the type of above properties is not Drawable
/String
, but Int
.
fun abc(a: Serializable)
where a is any (data) class with @Serializable annotation.
I don’t think this is possible in either Kotlin or Java. @Serializable
is not the type of a
, it is only an annotation. You could probably do this using some linter or other static analysis util.
Hm, when I tried to use an interface, I got this:
Class ‘RequestData’ is not registered for polymorphic serialization in the scope of ‘Serialize’.
To be registered automatically, class ‘RequestData’ has to be ‘@Serializable’, and the base class ‘Serialize’ has to be sealed and ‘@Serializable’.
Alternatively, register the serializer for ‘RequestData’ explicitly in a corresponding SerializersModule.
It really depends on when the annotation applies… as far as I know, most annotations are either used at runtime, or during the compilation to generate extra methods and stuff. I think the best you could do in this case is have a function that accepts Any
as a type, then inspect the argument at runtime using reflection to see if either it has the @Serializable
annotation on it, or if it has the generated function (according to the docs, the generated function ends up on the companion object).
Generally annotations don’t pass on via inheritance,
So the type system can’t even represent “classes with annotation @something”.
There’s @Inherited
which changes that behaviour, but, it’s a non-default option
https://docs.oracle.com/javase/8/docs/api/java/lang/annotation/Inherited.html