質問

さて、この質問は本当にばかげているように思えますが、私のポイントは、Scala 2.7.6 APIを見ると、mappingToStringメソッドが非推奨になっていることです。したがって、カスタム形式のマップを印刷するためのよりエレガントな代替手段が必要です。ほぼすべての目的のために、MapにmkStringの等価メソッドを持つことは本当に便利です。

皆さんはそれについてどう思いますか? println以外のマップを印刷するためのコーディングスニペットは何ですか?

役に立ちましたか?

解決

mappingToString メソッドを使用して、キー/値の各ペアをStringに変換する方法を変更し、 toString メソッドで使用しました。

それはお粗末なフィットだと思います。それは、他の点では不変のデータ構造に可変性を追加します。特定の印刷要件がある場合は、おそらく別のクラスに入れる方が良いでしょう。

他のヒント

mappingToString Map に固有のものでした。

Scala2.8の新しいコレクションフレームワークでは、 Map IterableLike で反復処理できます。 .ch / trac / scala / browser / scala / trunk / src / library / scala / collection / TraversableLike.scala "rel =" nofollow noreferrer "> TraversableLike 。

メソッド mkstring Iterable )を使用する必要があります。

こちらをご覧くださいブログ投稿" Strings" 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

たとえば、 map [String、String]からクエリ文字列を作成するために、 Iterator.map() mkString()を組み合わせることもできます。

val queryString = updatedMap.map(pair => pair._1+"="+pair._2).mkString("?","&","")
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top