How do you pass a variable to a custom string interpolator

scala, string-interpolation

Solution

- String interpolation translates to direct method call at compile time, so you can't use it on variables

I'm not sure that I understand you correctly, but you can try implicit parameters:

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")

as @didier-dupont suggests you can use second parameters list without implicits:

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))

Problem

In the worksheet below, I've created a custom string interpolator. ``` 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 } ``` I have two questions regarding this: - How do you use the string interpolator on variables - How do you pass or use an additional argument to your string interpolator. Say for example my string interpolator is used to lookup variables from a file, but I want to specify the file name on the fly?

Original source