2
votes

I want to annotate with @JsonCreator using a primary constructor, something like this:

// error
@JsonCreator class User(
    @JsonProperty("username") var username: String,
    @JsonProperty("password") var password: String
) {
  // ...
}

But the @JsonCreator annotation gives an error "This annotation is not applicable to target 'class'".

Using a secondary constructor works, but is it the only (or best) way?:

// works, but is there a better way?
class User @JsonCreator constructor(
    @JsonProperty("username") var username: String,
    @JsonProperty("password") var password: String
) {
  // ...
}
1
That's not a secondary constructor. It's the primary one. kotlinlang.org/docs/reference/classes.html#constructors If the primary constructor does not have any annotations or visibility modifiers, the constructor keyword can be omitted - JB Nizet

1 Answers

10
votes

What you describe here:

class User @JsonCreator constructor(
    @JsonProperty("username") var username: String,
    @JsonProperty("password") var password: String
) {
  // ...
}

is actually explicitly specifying the primary constructor. You can differentiate the primary from the secondary by looking at the class declaration:

class User constructor(/** **/) { // <-- primary

    constructor(/** ... **/) { // <-- secondary

    }

}

if the constructor is part of the class header it is a primary constructor, if it is part of the class declaration (it is after the {) it is a secondary one.