How to print a list of strings to standard error in Scala?

18,339

Solution 1

Even not being able to exactly reproduce the problem, I do know you can solve the ambiguity by specifying the type:

scala> List("a","b","c")
res0: List[java.lang.String] = List(a, b, c)

scala> res0.foreach(System.err.println(_:String))
a
b
c

In this example the _:String is unnecessary, it maybe necessary in your use case.

Solution 2

According to RosettaCode, calling the built-in Console API is better than calling the Java runtime library with System.err:

scala> List("aa", "bb", "cc").foreach(Console.err.println(_))
aa
bb
cc
Share:
18,339

Related videos on Youtube

ektrules
Author by

ektrules

Updated on September 15, 2022

Comments

  • ektrules
    ektrules over 1 year

    This line causes a compile error:

    astgen.typeError.foreach(System.err.println)
    

    typeError is a scala.collection.immutable.List of Strings in the object astgen.

    The error I'm getting is:

    error: ambiguous reference to overloaded definition,
    both method println in class PrintStream of type (java.lang.String)Unit
    and  method println in class PrintStream of type (Array[Char])Unit
    match expected type (Nothing) => Unit
          astgen.typeError.foreach(System.err.println)
    

    I'm new to Scala and don't understand the problem. Using 2.7.7final.

    • pedrofurla
      pedrofurla over 11 years
      I could reproduce the problem in version 2.9.1. Which version are you using? Are you talking about scala's List or Java's?
    • soc
      soc over 11 years
      You should consider upgrading, 2.7.7 is pre-historic. This issue has been fixed in a more recent version.
    • pedrofurla
      pedrofurla over 11 years
      Ops, I meant I couldn't reproduce the problem in 2.9.1. And indeed @soc is right, 2.7.7 is paleolithic.
  • kap
    kap almost 7 years
    Only System.err logs to stderr as Logback target. Console.err does not work when specified as target, it then still logs to stdout.