简体   繁体   English

在scala中使用数组参数格式化字符串

[英]Format string with array argument in scala

I have next list and string: 我有下一个列表和字符串:

val s = List(JSONObject, JSONObject, JSONObject)
val data = s"""[${s(0)}, ${s(1)}, ${s(2)}]"""

Is it possible to pass list to s function, so I won't get list elements by index? 是否可以将列表传递给s函数,所以我不会按索引获取列表元素?

You're looking for mkString : 您正在寻找mkString

List(
  JSONObject(Map("hello" -> "world", "stackoverflow" -> "ishere")),
  JSONObject(Map("1" -> 1))
).map(_.toString()).mkString(", ")

Yields: 产量:

scala> :pa
// Entering paste mode (ctrl-D to finish)

List(
  JSONObject(Map("hello" -> "world", "stackoverflow" -> "ishere")),
  JSONObject(Map("1" -> 1))
).map(_.toString()).mkString(", ")

// Exiting paste mode, now interpreting.

res2: String = {"hello" : "world", "stackoverflow" : "ishere"}, {"1" : 1}

Try This 尝试这个

val s = List("JSONObject", "JSONObject", "JSONObject")
val result = s.mkString("[",",","]")
result: String = [JSONObject,JSONObject,JSONObject]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM