Ekk*_*anz 5 formatting scala map
好吧,这个问题似乎真的很愚蠢,但我的观点是,如果你看一下Scala 2.7.6 API,他们就不推荐使用mappingToString方法了.因此,应该有更优雅的替代方案来打印自定义格式的Map.因为几乎任何目的,在Map中使用mkString的等价方法非常方便.
你们怎么看待它?除println外,打印地图的编码片段是什么?
mappingToString是特定于Map.
使用 Scala2.8 中新的集合框架,可以通过扩展TraversableLikeMap的任何对象来迭代a 。IterableLike
然后应该使用mkstring方法(2.7 for 中已有)。Iterable
请参阅 Jesse 的这篇博客文章“Strings”,了解 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
Run Code Online (Sandbox Code Playgroud)
该mappingToString方法用于更改每对键/值转换为字符串的方式,然后由该toString方法使用。
我认为这很糟糕。一方面,它为原本不可变的数据结构添加了可变性。如果您有特定的打印要求,那么您最好将它们放在另一个类中。
| 归档时间: |
|
| 查看次数: |
20690 次 |
| 最近记录: |