Scala Type aliases for annotations

后端 未结 3 716
栀梦
栀梦 2021-01-02 02:33

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

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

where null

相关标签:
3条回答
  • 2021-01-02 03:03

    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).

    0 讨论(0)
  • 2021-01-02 03:04

    Does this work?

    type MyAnnotation[+X] = @BeanProperty
                            @(SpaceProperty @beanGetter)(nullValue = 0) X
    
    val myValue: MyAnnotation[MyType] 
    
    0 讨论(0)
  • 2021-01-02 03:07

    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.

    0 讨论(0)
提交回复
热议问题