在下面的工作表中,我创建了一个自定义字符串插值器。
object WSLookup {
implicit class LookupSC(val sc: StringContext) extends AnyVal {
def lookup(args: Any*): String = {
val strings = sc.parts.iterator
val expressions = args.iterator
var buf = new StringBuffer(strings.next)
while (strings.hasNext) {
buf append doLookup(expressions.next.toString)
buf append strings.next
}
buf.toString()
}
def doLookup(s: String): String = {
// Just change the string to uppercase to test.
s.toUpperCase
}
}
val x = "cool"
val testString = "Not $x"
lookup"How $x"
// lookup testString //<--- See question 1
}
我有两个问题:
答案 0 :(得分:5)
我不确定我是否理解正确,但您可以尝试隐式参数:
implicit class TestInt(val sc: StringContext) extends AnyVal {
def test(args: Any*)(implicit prefix: String): String =
prefix + sc.s(args:_*)
}
implicit val p = "> "
val x = 1
println(test"x = $x")
正如@ didier-dupont建议你可以使用第二个参数列表而不暗示:
implicit class TestInt(val sc: StringContext) extends AnyVal {
def test(args: Any*)(prefix: String): String =
prefix + sc.s(args:_*)
}
val p = "> "
val x = 1
println(test"x = $x"(p))