3

Annotations in Kotlin can have different use-site targets as explained here: https://kotlinlang.org/docs/reference/annotations.html#annotation-use-site-targets

My question is: When use-site is not explicitly defined, what is the default target when annotating property in a class like in the example below?

class Test {
  @SomeAnnotation
  var someProperty: String? = null
}

Background

I'm trying Jongo as MongoDB client in Kotlin and have problems annotating id field. Jongo does not map id property correctly when it's annotated like this:

@MongoId @MongoObjectId var id: String? = null

The annotations in question are just meta-annotations for Jackson. However it seems to work when I annotate the property like this, indicating use-site problem:

@field:[MongoId MongoObjectId]
var id: String? = null

I would expect that @field is default use-site, but it seems that it isn't.

Krešimir Nesek
  • 5,302
  • 4
  • 29
  • 56

1 Answers1

7

The reference says:

If you don’t specify a use-site target, the target is chosen according to the @Target annotation of the annotation being used. If there are multiple applicable targets, the first applicable target from the following list is used:

  • param (constructor parameter)
  • property (annotations with this target are not visible to Java)
  • field

So if your annotation has @Target({ElementType.FIELD}), the annotation in Kotlin will target @field:.

If it has no @Target specified, it may be used on any program element: the @property: target is also applicable and is chosen by default.

hotkey
  • 140,743
  • 39
  • 371
  • 326
  • Ah.. I somehow missed that part even though I was actively looking for it. This explains why mapping doesn't work without specifying @field. MongoId doesn't have TARGET, and property annotations are not visible to Java. Since Jongo uses Jackson which expects annotation on field or getter, it cannot see the annotation. – Krešimir Nesek Feb 12 '16 at 12:38
  • @KresimirNesek you want it on the getter for Jackson, so `@get:SomeAnnotation` for the property. – Jayson Minard Feb 12 '16 at 20:11