[英]Scala opening write to stdout or file
Let's say I have a function 假设我有一个功能
writeToFileOrStdout(fname: String = Nil) = { ... }
If the user passes a string value for fname, then I'd like to open a file with that name and write to it; 如果用户为fname传递字符串值,那么我想打开一个具有该名称的文件并写入该文件; otherwise, I'd like to print to stdout.
否则,我想打印到标准输出。 I could always just write an if statement to take care of this, but how would I write a case statement on fname and open the correct corresponding outputStream?
我总是可以写一个if语句来解决这个问题,但是我将如何在fname上写一个case语句并打开正确的对应outputStream?
val outStream = fname match {
case Nil => ???
case _ => new java.io.FileOutputStream(new java.io.File(fname))
}
outStream.write( ... )
Thanks! 谢谢!
Why not rewrite the function as: 为什么不将函数重写为:
def writeToFileOrStdout(fname: Option[String] = None) = {
val outStream = fname match{
case Some(name) => new java.io.FileOutputStream(new java.io.File(name))
case None => System.out
}
...
}
It's always a good idea to use Option
for an optional input as opposed to using null
. 最好将
Option
用作可选输入,而不是使用null
。 That's basically what it's there for. 这基本上就是它的用途。 In good scala code, you will not see explicit references to
null
. 在良好的Scala代码中,您将看不到对
null
显式引用。
In fact, your code doesn't even compile for me. 实际上,您的代码甚至没有为我编译。
Nil
is used to represent an empty list, not a null or non supplied String
. Nil
用于表示一个空列表,而不是null或未提供的String
。
To augment cmbaxter's response... 为了增强cmbaxter的响应...
Mapping a String
with a possible null
value to Option[String]
is trivial: Option(stringValue)
will return None
where stringValue
is null
, and Some(stringValue)
where non-null. 将具有可能为
null
值的String
映射到Option[String]
是很简单的: Option(stringValue)
在stringValue
为null
将返回None
,在非null时将返回Some(stringValue)
。
Thus, you can either: 因此,您可以:
writeToFileOrStdout(Option(stringValue))
, or writeToFileOrStdout(Option(stringValue))
,或
If you're stuck on String
(and possibly a null
value) as the parameter to writeToFileOrStdout
, then internally use Option(fname)
and match to what it returns:: 如果您将
String
(可能为null
值)作为writeToFileOrStdout
的参数,则在内部使用Option(fname)
并匹配它返回的内容:
def writeToFileOrStdout(fname: String = null) = { val outStream = Option(fname) match{ case Some(name) => new java.io.FileOutputStream(new java.io.File(name)) case None => System.out } ... }
To further augment cmbaxter's response, you might consider writing this: 为了进一步增强cmbaxter的响应,您可以考虑编写以下代码:
def filenameToOutputStream(name: String) =
new java.io.FileOutputStream(new java.io.File(name))
def writeToFileOrStdout(fname: Option[String] = None) = {
val outStream = fname map filenameToOutputStream getOrElse System.out
...
}
As the post Idiomatic Scala: Your Options Do Not Match suggests, this might be more idiomatic Scala. 正如“惯用Scala :您的选项不匹配”一文所暗示的那样,这可能是更惯用的Scala。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.