我有一个带有一些可选属性的对象,我想在字符串模板中列出这些属性(以某种 JSON 方式)如果该属性是 None 我不想看到任何东西,如果它是 Non None 我想看到一个带有值的标签:
case class FooTest(a: String, b: Option[String], c: String)
val test = FooTest("one", Some("two"), "three");
val myTemplate = s"""
| "een" : "${test.a}"
| ${test.b.fold(""){tb => s"\"twee\": \"$tb\"}
| "drie" : "${test.c}"
"""
这与
Some("value")
的预期效果一致,但它为 test.b
留下了一个空行
None
对于test.b
:
"een" : "one"
"drie" : "three"
如何摆脱空行(除了在结果字符串中用 1 个换行符替换 2 个后续换行符之外)?
一种可能性可能是内联第二行并显式添加换行符,这有点工作,但与缩进的交互不太好:
case class FooTest(a: String, b: Option[String], c: String)
def template(test: FooTest) = s"""
| "een" : "${test.a}"${test.b.fold(""){tb => s"\n\"twee\": \"$tb\""}}
| "drie" : "${test.c}"
""".stripMargin
println(template(FooTest("one", Some("two"), "three")))
println(template(FooTest("one", None, "three")))
输出:
"een" : "one"
"twee": "two"
"drie" : "three"
"een" : "one"
"drie" : "three"
如果您想让模板字符串保持良好状态并与模板缩进配合良好,一种可能的方法是在第二遍中删除空行,如下所示:
case class FooTest(a: String, b: Option[String], c: String)
def template(test: FooTest) = s"""
| "een" : "${test.a}"
| ${test.b.fold(""){tb => s"\"twee\": \"$tb\""}}
| "drie" : "${test.c}"
""".stripMargin
def deleteEmptyLines(s: String) = s.replaceAll("\\n\\s*\\n", "\n")
println(deleteEmptyLines(template(FooTest("one", Some("two"), "three"))))
println(deleteEmptyLines(template(FooTest("one", None, "three"))))
输出:
"een" : "one"
"twee": "two"
"drie" : "three"
"een" : "one"
"drie" : "three"
您可以在 Scastie 上使用此代码。