以下のワークシートでは、カスタム文字列補間を作成しました。
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
}
これに関して2つの質問があります。
- 変数で文字列補間をどのように使用しますか
- 文字列補間器に追加の引数を渡すか、使用するにはどうすればよいですか。たとえば、私の文字列補間器を使用してファイルから変数を検索するとしますが、ファイル名をその場で指定したいですか?