26

Annotating constructor parameters seems to do nothing when compiled to bytecode. I get no compiler warnings either.

The following works. getAnnotations for the name field returns javax.annotation.Nullable.

class Person {
    @Nullable var name: String = _;
}

The following doesn't, neither with val or var.

class Person(@Nullable var name: String)

This is probably not intentional, so is there something I am missing or should I go file a bug report?

1 Answer 1

36

You need to specify what should get annotated when you specify annotations on constructor parameters.

To do that annotate your annotation with one ore more annotations from scala.annotation.target, e.g. getter, setter or as in your case field:

import annotation.target.field

class Person(@(Nullable @field) var name: String)

You can also use type aliases for that:

type NullableField = Nullable @field

class Person(@NullableField var name: String)

Update Scala 2.12

Now this specific annotation and others are in the package scala.annotation.meta rather than scala.annotation.target

import scala.annotation.meta.{field, param}
Sign up to request clarification or add additional context in comments.

3 Comments

The corresponding documentation is now at scala-lang.org/api/current/#scala.annotation.meta.package
That documentation link didn't work for me, but this does: scala-lang.org/api/2.12.4/scala/annotation/meta/index.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.