Search code examples
scalaannotations

Usage of @field annotations


I was perusing the spray-swagger library and came across this piece of code:

@ApiModel(description = "A pet object")
case class Pet(
  @(ApiModelProperty @field)(value = "unique identifier for the pet")
  val id: Int,

  @(ApiModelProperty @field)(value = "The name of the pet")
  val name: String)

I went to my trusty copy of Programming In Scala 3ed to find out what syntax of using the @field annotation within another annotation (re: @(ApiModelProperty @field)) but I came up short. I cracked open the @ApiModelProperty code and found:

/**
 * Adds and manipulates data of a model property.
 */
@Target({ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface ApiModelProperty {

Question: Are we providing the compiler clues as to what context the @ApiModelProperty annotation applies in order to satisfy its @Target annotation?


Solution

  • You can find the answer in the documentation for scala.annotation.target package.

    The @field meta-annotation is used to tell the compiler that the actual field named id should be considered the target of the annotation, as opposed to the automatically generated accesssor/mutator methods:
    id():Int and id_=(i: Int):().