12

In many points of my code, three annotations appears together:

@BeanProperty
@(SpaceProperty @beanGetter)(nullValue="0")

where nullValue="0" is a parameter to the annotation SpaceProperty.

Is it possible to define a single type alias for @BeanProperty @(SpaceProperty @beangetter) ?

The best I could do was:

type ScalaSpaceProperty = SpaceProperty @beanGetter

@BeanProperty
@(ScalaSpaceProperty)(nullValue = "0")

Is it possible to define a type alias for two annotations where the parameters are applied to the last one?

kiritsuku
  • 52,967
  • 18
  • 114
  • 136
Edmondo
  • 19,559
  • 13
  • 62
  • 115

3 Answers3

4

No. You can write a macro to do this in Scala 2.10, I think (but the documentation isn't available at the moment, so I can't check).

Alexey Romanov
  • 167,066
  • 35
  • 309
  • 487
4

The only example of type aliasing annotations I know is in Scaladoc. Below follows the relevant part:

object ScalaJPA {
  type Id = javax.persistence.Id @beanGetter
}
import ScalaJPA.Id
class A {
  @Id @BeanProperty val x = 0
}

This is equivalent to writing @(javax.persistence.Id @beanGetter) @BeanProperty val x = 0 in class A.

type declarations can only deal with types. In other words you can't provide instance information in type aliases.

One alternative is to try to extend the annotation. Below I created an hypothetical SpaceProperty for illustrative purposes:

scala> import scala.annotation._; import scala.annotation.target._; import scala.reflect._;
import scala.annotation._
import scala.annotation.target._
import scala.reflect._

scala> class SpaceProperty(nullValue:String="1",otherValue:Int=1) extends Annotation with StaticAnnotation

scala> class SomeClass(@BeanProperty @(SpaceProperty @beanGetter)(nullValue="0") val x:Int)
defined class SomeClass

scala> class NullValueSpaceProperty extends SpaceProperty(nullValue="0")
defined class NullValueSpaceProperty

scala> class SomeClassAgain(@BeanProperty @(NullValueSpaceProperty @beanGetter) val x:Int)
defined class SomeClassAgain

Using the type alias:

scala> type NVSP = NullValueSpaceProperty @beanGetter
defined type alias NVSP

scala> class SomeClassAgain2(@BeanProperty @NVSP val x:Int)defined class SomeClassAgain2

There one small problem with this solution. Annotations defined in Scala couldn't be retained during runtime. So if you need to use the annotation during runtime, you may need to do the extension in Java. I say may because I am not sure if this limitation already has been amended.

pedrofurla
  • 12,763
  • 1
  • 38
  • 49
0

Does this work?

type MyAnnotation[+X] = @BeanProperty
                        @(SpaceProperty @beanGetter)(nullValue = 0) X

val myValue: MyAnnotation[MyType] 
Ptharien's Flame
  • 3,246
  • 20
  • 24