Search code examples
scalastring-interpolation

Is it possible to specify type parameters for String Interpolation in Scala


implicit class Interpolator(val a: StringContext) extends AnyVal {
  def foo[A](args: Any*): A = ???
}

val first  = foo[String]"myString" // This does not parse
val second = (new StringContext).foo[String]("myString") // This works but I'm wondering if there is a more concise syntax
val third = foo"myString"[String] // This one is intriguing because it parses but the compiler outputs "method foo does not take type parameters"... what?

If A can be inferred then it's all good because foo"myString" will simply work but if it can't I am wondering if there is a better syntax than second that allows me to specify the type parameter I expect.


Solution

  • Second only compile but it doesn't really work, we can try for example

    implicit class Interpolator(val a: StringContext) {
        def foo[A](args: Any*): A = args.head.asInstanceOf[A]
    }
    
    val a = 2
    val second = (new StringContext)foo[String]"a=$a"
    println(second)// this will print a=$a which is not the expected output
    

    But the following should work

    implicit class Interpolator[A](val a: StringContext)  {
        def foo(args: Any*): A = args.head.asInstanceOf[A]
    }
    
    val a = 2
    val first :Int = foo"a=$a" // : Int is what that does the trick
    println(first) // will print 2 as expected