Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

io

scala

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.

like image 919
ektrules Avatar asked Oct 15 '12 02:10

ektrules


2 Answers

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.

like image 159
pedrofurla Avatar answered Nov 01 '22 17:11

pedrofurla


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
like image 34
Benoit Avatar answered Nov 01 '22 16:11

Benoit