用于映射 getOrElse 的 scala 更好的语法 [英] scala better syntax for map getOrElse
问题描述
有没有更好的方法来编写下面的代码?
is there a better way to write the code below?
val t = map.get('type).getOrElse("");
if (t != "") "prefix" + t;
对内联代码感兴趣
val t = map.get('type).getOrElse("").????
推荐答案
Map
有自己的 getOrElse
方法,所以你可以写如下:
Map
has its own getOrElse
method, so you can just write the following:
val t = map.getOrElse('type, "")
在您的第一个示例中完成与 t
的定义相同的事情.
Which accomplishes the same thing as the definition of t
in your first example.
解决您的评论:如果您知道您的地图永远不会包含空字符串作为值,您可以使用以下内容添加前缀"
:
To address your comment: If you know your map will never contain the empty string as a value, you can use the following to add the "prefix"
:
map.get('type).map("prefix" + _).getOrElse("")
或者,如果您使用的是 Scala 2.10:
Or, if you're using Scala 2.10:
map.get('type).fold("")("prefix" + _)
如果您的地图可以具有 ""
值,则此版本的行为将与您的略有不同,因为它将为这些值添加前缀.如果您希望在单行中与您的版本完全相同,则可以编写以下内容:
If your map can have ""
values, this version will behave a little differently than yours, since it will add the prefix to those values. If you want exactly the same behavior as your version in a one-liner, you can write the following:
map.get('type).filter(_.nonEmpty).map("prefix" + _).getOrElse("")
不过,这可能不是必需的 - 听起来您不希望地图中有空字符串.
This probably isn't necessary, though—it sounds like you don't expect to have empty strings in your map.
这篇关于用于映射 getOrElse 的 scala 更好的语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!