scalaconsolestdoutstderroutput-redirect

Redirect both stdout and stderr to output stream in Scala


What I'd like to do in Scala is redirect both standard output and standard error to output streams. I am aware of scala.Console.withOut and scala.Console.withErr but it seems I need to call these functions separately, which leads to running my command (function) twice:

scala.Console.withOut(out)(f)
scala.Console.withErr(out)(f)

I'd like to call f only once and get both out and err in streams.


Solution

  • You can nest them:

    Console.withOut(out) {
      Console.withErr(out) {
        f
      }
    }