kotlinx.serialization icon indicating copy to clipboard operation
kotlinx.serialization copied to clipboard

Make annotation inheritable for fields

Open Chuckame opened this issue 4 months ago • 2 comments

What is your use-case and why do you need this feature? I would like to have my annotations inherited from the super-type, to avoid redondant code.

Currently, it is not possible at all to inherit custom annotations, or even kotlinx-serialization annotations:

@SerialInfo
@InheritableSerialInfo // <--- works only for classes
@Target(AnnotationTarget.PROPERTY)
public annotation class AvroDoc(val value: String)

@Serializable
sealed interface SuperType {
    @AvroDoc("super type doc")
    @SerialName("customFieldName")
    val str: String

    @Serializable
    data class Foo(override val str: String) : SuperType
}

The generated descriptor contains an element with the name str instead of the name set in the upper level customFieldName, and the AvroDoc annotation isn't visible as Foo.serializer().descriptor.getElementAnnotations(0) returns an empty list.

I also had a look to kotlin docs, and there is no way to inherit annotations. A ticket is open for that purpose: https://youtrack.jetbrains.com/issue/KT-22265?_gl=11f00hr0_gcl_auMTkwODk0NDI4Ni4xNzQ4NzAzOTQ3_gaNjEzNjUzMTA3LjE3MTQ2OTM4MDk._ga_9J976DJZ68*czE3NTUxNTQ1OTMkbzE2JGcxJHQxNzU1MTU0ODE3JGo5JGwwJGgw

Describe the solution you'd like Allow inheritance natively without configuration, or even with explicit annotation with the existing annotation InheritableSerialInfo or with a new annotation like InheritableElementSerialInfo

Chuckame avatar Aug 12 '25 16:08 Chuckame

Annotation inheritance can be very fiddly. It can easily break if you have more than one super interface with the same property name, or if there's Java- or non-serializable-Kotlin class in the middle of hierarchy. So I would say this behavior may bring more unnecessary debugging troubles rather than benefits.

sandwwraith avatar Aug 18 '25 13:08 sandwwraith

I agree that it could give more issues than expected. But shouldn't it be easily resolved by showing warnings from the serialization plug-in? With a simple ordering (the lower level annotations comes first), we can naturally get the most specific annotations. Then showing an error for annotations that aren't allowing repetition with different annotation parameters, for which you would be forced to explicit the annotation with the parameters you want.

Chuckame avatar Aug 18 '25 13:08 Chuckame