Compile Time Parameter for Macro Expansion

2019-07-23 17:34发布

I would like to write an annotation macro that adds an extends <sometype> to traits where <sometype> can be specified at compile time.

How can a compile time parameter be passed to a macro expansion? Ideally I would like to specify a command line argument at the compiler call.

标签: scala-meta
1条回答
Juvenile、少年°
2楼-- · 2019-07-23 18:09

Macro annotations don't have access to the command-line flags passed to scalac. However, one possible way to achieve this might be to use system properties.

For example, in the macro annotation implementation

// MyMacro.scala
val someType = sys.props.getOrElse("myapp.sometype", ???)

Then pass the type as a command line option

// command-line
scalac -Dmyapp.sometype=foobar Code.scala

Similarly, it's possible to run sbt -Dsometype=foobar compile. However, note that the JVM process needs to start with the system property flag, so setting scalacOptions += "-Dsometype=foobar" may not work.

查看更多
登录 后发表回答