2009-10-23 12 views
5

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

あなたはどう思いますか? println以外のMapを印刷するためのコーディングスニペットは何ですか?

答えて

3

mappingToString方法は、キー/値の各ペアは、その後toString方法によって使用された文字列に変換された方法を変更するために使用しました。

私はそれがひどいフィットだと思う。これは、他の方法では変更できないデータ構造に変更可能性を追加します。特定の印刷要件がある場合は、おそらく別のクラスに入れる方がよいでしょう。

+0

良い点を不変クラスであることに! – Ekkmanz

2

mappingToStringは、Mapに特異的であった。

Scala2.8の新しいコレクションフレームワークでは、MapIterableLike(これはTraversableLikeです)で繰り返すことができます。

Iterableの場合はmkstringのメソッド2.7)が使用されます。

2.7 mkstring()例については、このblog post "Strings" by Jesse参照:

/* 
    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 
3

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

val queryString = updatedMap.map(pair => pair._1+"="+pair._2).mkString("?","&","") 
関連する問題