Scala: code runs only during debugging (equivalent to #ifdef?)

In C ++, I can write:

#ifdef DEBUG cout << "Debugging!" << endl; 

Is there any equivalent in Scala?

+4
source share
3 answers

Traditional idiom @elidable.

The skydakop covers your usual use case:

http://www.scala-lang.org/api/current/scala/annotation/elidable.html

+7
source

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

+6
source

If you want the code to be executed only under certain conditions, you can use the standard if block:

 if (SystemProperties.get("debug.mode").exists(_ == "true") { println("Debugging!") } 

If you are worried for any reason that the statement should not appear even on the compiled output, you can use an if block with a constant expression of compilation time. In these cases, javac / scalac will correctly infer that the condition will never be true, and therefore will not even include the bytecode for the block. (Obviously, you will need to change your build to pull out the constant "true" for debug builds and "false" for the build prod.)

 object Constants { final val DEBUG = false } // ... if (Constants.DEBUG) { println("Debugging!") } 
-1
source

Source: https://habr.com/ru/post/1483413/


All Articles