문제

좋아,이 질문은 정말 어리석은 것 같지만, 내 요점은 Scala 2.7.6 API를 살펴보면 매핑 테스트 방법을 사용하지 않았다는 것입니다. 따라서 사용자 정의 형식지도를 인쇄하기위한 더 우아한 대안이 있어야합니다. 거의 모든 목적으로 맵에서 동등한 방법을 갖는 것은 정말 편리합니다.

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

도움이 되었습니까?

해결책

그만큼 mappingToString 메소드는 각 키/값 쌍이 String으로 변환되는 방식을 변경하는 데 사용되었으며 toString 방법.

나는 그것이 어색한 것 같아요. 그것은 다른 불변의 데이터 구조에 돌연변이를 추가합니다. 특정 인쇄 요구 사항이 있다면 다른 클래스에 넣는 것이 좋습니다.

다른 팁

mappingToString 특정이었다 Map.

Scala2.8의 새로운 컬렉션 프레임 워크와 함께 a Map 어떤 것도 반복 할 수 있습니다 IterableLike 확장됩니다 트래버스블 라이브.

방법 mkstring (이미 2.7에 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

당신은 또한 결합 할 수 있습니다 Iterator.map() ~와 함께 mkString(), 예를 들어 a에서 쿼리 스트링을 생성합니다 map[String,String]:

val queryString = updatedMap.map(pair => pair._1+"="+pair._2).mkString("?","&","")
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top