The equivalent form of a C # ifdef preprocessor is a Scala macro:
package app.macros.log import scala.language.experimental.macros import reflect.macros.Context object SimpleMacroLogger { private val on = true def info(msg: String): Unit = macro info_impl def info_impl(c: Context)(msg: c.Expr[String]): c.Expr[Unit] = { import c.universe._ if (on) { reify { println(msg.splice) } } else { reify { // Nothing } } } }
for use with
import app.macros.log.{SimpleMacroLogger => log} object SimpleMacroLoggerDemo extends App { log.info("Hello") }
This is much more difficult for the code, but its use is superior: there is no need for the environment # ifdef / # endif, etc. This way it does not clutter up your code.
If you set it to false, the macro will completely delete the entry.
Everything that is contained in reify will go into the received bytecode, another code is run at compile time. This is especially true for if (on) ....
source share