scala 如何在Scala中将字符串列表打印为标准错误?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12888455/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 04:38:10  来源:igfitidea点击:

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

scalaio

提问by ektrules

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.

typeError 是对象 astgen 中的 scala.collection.immutable.List 字符串。

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.

我是 Scala 的新手,不明白这个问题。使用 2.7.7final。

回答by pedrofurla

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 _:Stringis unnecessary, it maybe necessary in your use case.

在这个例子中_:String是不必要的,在你的用例中可能是必要的。

回答by Benoit

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

根据RosettaCode,调用内置ConsoleAPI 比调用 Java 运行时库更好System.err

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