Vitaly Chirkov
Vitaly Chirkov

Reputation: 1712

How to apply annotation to getter of delegated property in Kotlin?

While Using Kotlin I wanted to add package-defined constant as a prefix for serialized class property. Jackson is bro, so I wrote this:

var prop: String = ""
    @JsonGetter(value = "prop")
    get() = PREFIX + field

It worked fine, so I decided to replace it with delegated property for brevity:

@get:JsonGetter(value = "prop") var prop: String by PrefixedProperty()

...

class PrefixedProperty(var field: String = "") {
    operator fun getValue(blah blah) = PREFIX + field
    ...
}

And BOOM — my property disappeared.

It seems, annotation was not applied to prop's delegated getter. Is it even possible to achieve the desired behaviour?

Upvotes: 2

Views: 633

Answers (1)

Yashar Shahi
Yashar Shahi

Reputation: 11

You should annotate it like this:

@delegate:JsonGetter(value = "prop") var prop: String by PrefixedProperty()

Upvotes: 1

Related Questions