1

我有 println(something) 的要求,但没有 println 任何东西,也没有打印新行,我怎么能在 Scala 中做到这一点?println 上面的“东西”应该是什么才能满足我的要求?

4

4 回答 4

1

I'm just relating Florian Hars reply from the google scala-user mailing list, which seems to better frame the point.

Let me restate your problem: you have an assignment where you need to ignore comments while parsing some code source file.

Actually you have a main definition to test the assignment which prints out the result of parsing the source file, and you want the println statement to ignore the parsed comments, so the teacher's condition will be met.

If this is the case, then the "correct" solution would not be to find a way to prevent println to print, but to modify the parser/lexer to avoid producing a parsed token when it encounters a comment.

The other way would just be a "trick" to get the assignment right by exploiting a particular "code configuration"...

于 2012-09-24T14:31:07.883 回答
1
scala> Console.setOut(new java.io.PrintStream(new java.io.OutputStream() { def write(b: Int) {} }))

scala> println("test")

scala>
于 2012-09-21T10:07:36.823 回答
0

println(...)无论您传递什么参数,都将始终打印一个换行符。没有办法阻止它打印换行符。

嗯...当然有下面的技巧,但它不是很实用。

class Magic {
  override def toString = throw new RuntimeException
}

// Will not print a newline, but will throw an exception
println(new Magic)

// So you'll need to catch it
try {
  println(new Magic)
} catch {
  case e: RuntimeException => // Ignore the exception
}

// Hey, we're here and no newline was printed!
于 2012-09-21T08:20:18.723 回答
-2

如果你还在运行 scala 解释器,你可以通过输入 :quit 命令退出它。将其放入名为 hello.scala 的文件中:

println("Hello, world, from a script!")

然后运行:

斯卡拉你好.scala

你应该得到另一个问候:

你好,世界,来自脚本!

于 2012-09-21T08:15:56.637 回答