假设我在Scala中有一个nexted Map,如下所示:
type MapType = Map[String, Map[String, Map[String, (String, String)]]]
val m: MapType = Map("Alphabet" -> Map( "Big Boss" -> Map("Clandestine Mssion" -> ("Dracula Returns", "Enemy at the Gates"))))
println(m)
这将输出Map,如下所示:
Map(Alphabet -> Map(Big Boss -> Map(Clandestine Mssion -> (Dracula Returns,Enemy at the Gates))))
我怎样才能像下面那样打印出来?:
Map(
Alphabet -> Map(Big Boss -> Map(
Clandestine Mssion -> (Dracula Returns,Enemy at the Gates)
)
)
)
或者以类似于非常嵌套的JSON的方式。
答案 0 :(得分:7)
这应该可以解决问题
object App {
def main(args : Array[String]) {
type MapType = Map[String, Map[String, Map[String, (String, String)]]]
val m: MapType = Map("Alphabet" -> Map( "Big Boss" -> Map("Clandestine Mssion" -> ("Dracula Returns", "Enemy at the Gates"))))
println(m.prettyPrint)
}
implicit class PrettyPrintMap[K, V](val map: Map[K, V]) {
def prettyPrint: PrettyPrintMap[K, V] = this
override def toString: String = {
val valuesString = toStringLines.mkString("\n")
"Map (\n" + valuesString + "\n)"
}
def toStringLines = {
map
.flatMap{ case (k, v) => keyValueToString(k, v)}
.map(indentLine(_))
}
def keyValueToString(key: K, value: V): Iterable[String] = {
value match {
case v: Map[_, _] => Iterable(key + " -> Map (") ++ v.prettyPrint.toStringLines ++ Iterable(")")
case x => Iterable(key + " -> " + x.toString)
}
}
def indentLine(line: String): String = {
"\t" + line
}
}
}
输出
Map (
Alphabet -> Map (
Big Boss -> Map (
Clandestine Mssion -> (Dracula Returns,Enemy at the Gates)
)
)
)
答案 1 :(得分:5)
这是一种使用类型类的方法,可避免强制转换和toString
。
trait Show[A] {
def apply(a: A): String
}
object Show {
def apply[A](f: A => String): Show[A] =
new Show[A] {
def apply(a: A): String = f(a)
}
}
implicit def showString: Show[String] = Show(identity)
implicit def show2[A, B](implicit sA: Show[A], sB: Show[B]): Show[(A, B)] =
Show({ case (a, b) => s"(${sA(a)}, ${sB(b)})" })
implicit def showMap[A, B](implicit sA: Show[A], sB: Show[B]): Show[Map[A, B]] =
Show(m => s"Map(\n${
m.map({
case (a, b) => s" ${sA(a)} -> ${sB(b).replace("\n", "\n ")}"
}).mkString(",\n")
}\n)")
def show[A](a: A)(implicit s: Show[A]): String = s(a)
val m = Map("Alphabet" -> Map("Big Boss" -> Map("Clandestine Mission" ->
("Dracula Returns", "Enemy at the Gates"))))
show(m)
结果:
Map(
Alphabet -> Map(
Big Boss -> Map(
Clandestine Mission -> (Dracula Returns, Enemy at the Gates)
)
)
)