Search code examples
scalaannotationsswagger

How to override case class field with annotation addition?


Question

How can I override a case class with annotation addition? Something like the following:

case class Foo (
  bar: Int
)

new Foo {
  @Annotation
  override val bar: Int
}

In the code above, I try to create an anonymous case class which overrides the field bar of the class Foo with the annotation @Annotation. Compiling returns "Illegal start of declaration @Annotation".

Context

I am trying to create a swagger documentation service but didn't want to litter the whole model classes with swagger annotations. I thought of creating anonymous case classes to be used only in the swagger API path annotations; these anonymous case classes will override the original model classes with swagger annotations.

It is used as something like:

new ApiImplicitParam(
  name = "body",
  dataTypeClass = classOf[DataType {
    @ApiModelProperty
    override val someEnum: SomeEnum
  }],
  required = true,
  paramType = "body"
)

Solution

  • Your code doesn't compile because you

    • don't provide argument for constructor

    and

    • don't implement bar.

    The following code compiles in 2.13

    new Foo(???) {
      @Annotation
      override val bar: Int = ???
    }