题
好的,这个问题似乎真的很愚蠢,但我的观点是,如果你看一下Scala 2.7.6 API,他们就不推荐使用mappingToString方法了。因此,应该有更优雅的替代方案来打印自定义格式的Map。因为几乎任何目的,在Map中使用mkString的等价方法非常方便。
你们怎么看待它?打印除println以外的地图的编码片段是什么?
解决方案
mappingToString
方法用于更改每对键/值转换为String的方式,然后由 toString
方法使用。
我觉得这很糟糕。一方面,它为其他不可变数据结构添加了可变性。如果您有特定的打印要求,那么最好将它们放在另一个类中。
其他提示
mappingToString
特定于 Map
。
使用Scala2.8中的新集合框架, Map
可以被任何 IterableLike
迭代,扩展 TraversableLike 。
方法 mkstring (已经在2.7中为 Iterable
)然后应该使用。
请参阅此博客文章“字符串”作者:Jesse ,2.7 mkstring()
例子:
/*
Making use of raw strings to create a multi line string
I add a | at the beginning of each line so that we can line up the quote nicely
in source code then later strip it from the string using stripMargin
*/
scala> val quote = """|I don-t consider myself a pessimist.
| |I think of a pessimist as someone who is waiting for it to rain.
| |And I feel soaked to the skin.
|
| |Leonard Cohen"""
quote: java.lang.String =
|I don-t consider myself a pessimist.
|I think of a pessimist as someone who is waiting for it to rain.
|And I feel soaked to the skin.
|Leonard Cohen
// capilize the first character of each line
scala> val capitalized = quote.lines.
| map( _.trim.capitalize).mkString("\n")
capitalized: String =
|I don-t consider myself a pessimist.
|I think of a pessimist as someone who is waiting for it to rain.
|And I feel soaked to the skin.
|Leonard Cohen
// remove the margin of each line
scala> quote.stripMargin
res1: String =
I don-t consider myself a pessimist.
I think of a pessimist as someone who is waiting for it to rain.
And I feel soaked to the skin.
Leonard Cohen
// this is silly. I reverse the order of each word but keep the words in order
scala> quote.stripMargin.
| lines.
| map( _.split(" ").
| map(_.reverse).
| mkString (" ")).
| mkString("\n")
res16: String =
I t-nod redisnoc flesym a .tsimissep
I kniht fo a tsimissep sa enoemos ohw si gnitiaw rof ti ot .niar
dnA I leef dekaos ot eht .niks
dranoeL nehoC
您还可以将 Iterator.map()
与 mkString()
结合使用,例如从 map [String,String]创建查询字符串代码>:
val queryString = updatedMap.map(pair => pair._1+"="+pair._2).mkString("?","&","")
不隶属于 StackOverflow