2012-10-15 31 views
12

这条线将导致编译错误:如何在Scala中打印出标准错误的字符串列表?

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

类型错误是一个字符串对象中的一个astgen scala.collection.immutable.List。

我得到的错误是:

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) 

我是新来的Scala和不理解的问题。使用2.7.7final。

+0

我可以重现该问题在2.9.1版本。你正在使用哪个版本?你在谈论Scala的List或Java? – pedrofurla

+1

你应该考虑升级,2.7.7是历史性的。此问题已在更新的版本中修复。 – soc

+0

Ops,我的意思是我无法在2.9.1中重现问题。确实@soc是对的,2.7.7是旧石器时代。 – pedrofurla

回答

15

即使不能够准确地重现该问题,我知道你可以通过指定型解决歧义:

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

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

在这个例子中_:String是不必要的,它在你的使用情况,也许有必要。

11

RosettaCode,调用内置Console API比调用Java运行时库System.err更好:

scala> List("aa", "bb", "cc").foreach(Console.err.println(_)) 
aa 
bb 
cc 
+0

只有'System.err'作为Logback目标记录到stderr。当指定为目标时,Console.err不起作用,它仍会记录到stdout。 – kap