-2

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

user10360768
  • 225
  • 3
  • 14

1 Answers1

1

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
)
Mateusz Kubuszok
  • 24,995
  • 4
  • 42
  • 64
  • I went with Ad 1 better sol. follow up question. I want to annotate with "@abc.xyz" and one more level e.g. "@abc.xyz.pqr" together. If I create another package xyz in abc and put pqr class in that, then I get this error: "package abc contains object and package with same name: xyz". How can I resolve this? Is it possible with class inside class? if yes how? – user10360768 Jan 29 '21 at 02:08