2009-10-23 3 views
5

좋아요,이 질문은 정말 바보 같은 것 같습니다. 그러나 요점은 스칼라 2.7.6 API를 살펴보면 mappingToString 메서드가 더 이상 사용되지 않는다는 것입니다. 따라서 사용자 정의 형식의 맵을 인쇄하기위한보다 세련된 대안이 있어야합니다. 거의 모든 목적을 위해 Map에서 mkString의 등가 메소드를 사용하는 것이 매우 편리합니다.스칼라에서지도 인쇄하는 법

너희들은 그것에 대해 어떻게 생각하니? println을 제외하고 Map을 인쇄하기위한 코딩 스 니펫은 무엇입니까?

답변

3

mappingToString 방법 키/값의 각각의 쌍은 다음 toString 방법에 의해 사용 된 문자열로 변환 된 방법을 변경하는 데 사용되었다.

나는 그게 형편없는 것 같아. 그것은 한 가지 다른 이유로 불변의 데이터 구조에 가변성을 추가합니다. 특정 인쇄 요구 사항이있는 경우 다른 클래스에 배치하는 것이 좋습니다.

+0

좋은 점을 불변 인 클래스 인에! – Ekkmanz

2

mappingToStringMap에 특정 적이었다.

Scala2.8의 새로운 컬렉션 프레임 워크에서 MapIterableLike으로 반복 될 수 있으며 TraversableLike으로 확장됩니다.

그런 다음 mkstring (이미 Iterable에 대해 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("?","&","")