ant2009
ant2009

Reputation: 22596

Confused about the following line @field:[Expose SerializedName("id")]

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:

Upvotes: 0

Views: 223

Answers (1)

gidds
gidds

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

Related Questions