21

How to convert the following Swagger annotations from Java to Kotlin?

 @ApiResponses(value = { @ApiResponse(code = 200, message = "Given admin user found"),
            @ApiResponse(code = 404, message = "..."),
            @ApiResponse(code = 500, message = "..."),
            @ApiResponse(code = 400, message = "..."),
            @ApiResponse(code = 412, message = "...") })

This does not works:

@ApiResponses(value = listOf( 
        ApiResponse(code = 200, message = "..."),
        ApiResponse(code = 404, message = "..."),
        ApiResponse(code = 500, message = "..."),
        ApiResponse(code = 400, message = "..."),
        ApiResponse(code = 412, message = "...") ))

The error is:

Type inference failed. Expected type mismatch: inferred type is List but ApiResponse was expected

It works when I use just one @ApiResponse instead of listOf(), but I have to define more @ApiResponse(s).

I use Swagger 2.5.0

Helen
  • 87,344
  • 17
  • 243
  • 314
Frido
  • 382
  • 5
  • 14
  • Annotations expect Arrays, not Lists, so try using the `arrayOf`-function instead of `listOf()` – Robin Jul 28 '17 at 13:10
  • Now I have got error: `Type inference failed. Expected type mismatch: inferred type is Array but ApiResponse was expected` – Frido Jul 28 '17 at 13:15
  • Yeah this is very odd. I'm tempted to say this might be a bug in Kotlin – Plog Jul 28 '17 at 13:22
  • Just tried it, actually you need to completly leave out the `value = listOf` part, and just put the individual arguments top level. Seems like kotlin translates a `value` that's an Array into varargs when called from Kotlin. – Robin Jul 28 '17 at 13:25
  • See my answer for the section in the Kotlin language reference that covers this and the code example that should work for you – Robin Jul 28 '17 at 13:30

2 Answers2

19

As stated in the Kotlin Language Reference:

If the value argument [of an Annotation] in Java has an array type, it becomes a vararg parameter in Kotlin

So, to make your example work, you need to put it like so:

@ApiResponses(
    ApiResponse(code = 200, message = "..."),
    ApiResponse(code = 404, message = "..."),
    ApiResponse(code = 500, message = "..."),
    ApiResponse(code = 400, message = "..."),
    ApiResponse(code = 412, message = "...")
)
Robin
  • 3,682
  • 2
  • 22
  • 26
10

For Swagger 3, this is the way to go:

 @ApiResponses(value = [
    ApiResponse(responseCode = "200", description = "...", content = [
        (Content(mediaType = "application/json", array = (
        ArraySchema(schema = Schema(implementation = DataModel::class)))))]),
    ApiResponse(responseCode = "400", description = "...", content = [Content()]),
    ApiResponse(responseCode = "404", description = "...", content = [Content()])]
    )

This snippet also includes @Content, @ArraySchema and @Schema annotation examples.

Sampada
  • 2,931
  • 7
  • 27
  • 39