Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Conversation

@haruue
Copy link

@haruue haruue commented May 23, 2025

Previously, getAttributesCode() did not correctly handle annotation instances inside annotation array parameters. For example, given:

annotation class AnnotationC(val s: String)
annotation class AnnotationD(
  val s: Array<AnnotationC>
)
interface API {
  @GET("/")
  @AnnotationD(s = [AnnotationC(s = "foo")])
  fun test()
}

Ktorfit would produce an _APIImpl class with the following code:

attributes.put(annotationsAttributeKey, listOf(
  AnnotationD(s = arrayOf(@com.example.AnnotationC(s = "foo"))),
))

Note the syntax error: when an annotation is used as a value (not as an annotation on a declaration), the leading @ should be omitted.

Actually, in KotlinPoet, this kind of value could be generated by using

AnnotationSpec.emit(..., asParameter = true)

or

CodeWriter.emitCode(..., isConstantContext = true)

However, none of those APIs are public. 😢

As a workaround, this patch generates the code for the whole AnnotationSpec and removes the prefixed @, which is the simplest solution I can find.

🤔 DOD Checklist

  • I did all relevant changes to the documentation and the changelog.

Previously, getAttributesCode() did not correctly handle annotation
instances inside annotation array parameters. For example, given:

  annotation class AnnotationC(val s: String)
  annotation class AnnotationD(
    val s: Array<AnnotationC>
  )
  interface API {
    @get("/")
    @AnnotationD(s = [AnnotationC(s = "foo")])
    fun test()
  }

Ktorfit would produce an _APIImpl class with the following code:

  attributes.put(annotationsAttributeKey, listOf(
    AnnotationD(s = arrayOf(@com.example.AnnotationC(s = "foo"))),
  ))

Note the syntax error: when an annotation is used as a value (not as an
annotation on a declaration), the leading '@' should be omitted.

Actually, in KotlinPoet, this kind of value could be generated by using
  AnnotationSpec.emit(..., asParameter = true)
or
  CodeWriter.emitCode(..., isConstantContext = true)

However, none of those APIs are public.

As a workaround, this patch generates the code for the whole
AnnotationSpec and removes the prefixed '@', which is the simplest
solution I can find.
@haruue haruue requested a review from Foso as a code owner May 23, 2025 13:04
@dewantawsif
Copy link
Contributor

Add a test case for this

@haruue haruue marked this pull request as draft May 29, 2025 06:48
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants