Reputation: 22596
I have the following data class that will retrieve data from an API:
data class Users(
@field:[Expose SerializedName("id")]
val id: Int)
I am just wondering what the @field:
means.
Normally, I have always done like this:
data class Users(
@Expose
@SerializedName("id")
val id: Int)
I understand the meaning of expose and serializedName.
Just a few questions:
My best guess would be for the @field:[]
would be to take an array of annotations, instead of putting them on each line as in the second example?
But is the field a Kotlin keyword or an annotation as it's preceded by the @
?
Where else could you use the @field?
Upvotes: 0
Views: 223
Reputation: 18607
The val id
in your example is declaring several different things in one go:
A constructor parameter.
A property of the class, implemented as a getter method.
A backing field for the property.
So which of those does an annotation get applied to? It defaults to the parameter, and that's what your second example does.
If you want it to apply to the field instead, as in your first example, you use the field:
target.
(It usually applies to single annotations, but it can apply to an array of them, as in this case.)
For more details, see the link jonrsharpe provided: https://kotlinlang.org/docs/reference/annotations.html#annotation-use-site-targets
The field:
, property:
, file:
, &c targets are only for use with annotations. (field
is also a keyword within getter/setter definitions.)
Upvotes: 1