Search code examples
scalaannotationscase-class

Custom annotations in scala


I am working in Scala programming language. I want to create custom annotations to annotate the fields of case class.

this thread show how to create it but there are two problems I am facing for my scenario

  1. There can be . in the annotations. e.g. @abc.xyz
  2. I want to create annotations without parameters. so I cannot create case classes

How can I do this?

Thanks


Solution

  • Ad. 1 - you can use backticks to have . in name but there I see 0 reasons why you should (you can just put xyz in abc package)

    // possible but it's anti-pattern
    class `abc.xyz` extends scala.annotation.StaticAnnotation
    
    case class Test(
      @`abc.xyz` field: String
    )
    
    // better
    package my.abc
    
    class xyz extends scala.annotation.StaticAnnotation
    
    // elsewere
    
    import my.abc
    
    case class Test(
      @abc.xyz field: String
    )
    

    Ad. 2 what annotations parameters have to do with case classes? Annotation does NOT have to be a case class. Some people use it because in macros they can use pattern matching on materialized annotation value, but that's it.

    case class Foo() extends scala.annotation.StaticAnnotation
    
    class Bar extends scala.annotation.StaticAnnotation
    
    case class Test(
      @Foo foo: String,
      @Bar bar: String
    )