是否可以在 Scala 中为字符串插值指定类型参数

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?

如果可以推断 A 那么一切都很好,因为 foo"myString" 可以简单地工作,但如果不能,我想知道是否有比 second 更好的语法允许我指定我期望的类型参数。

第二次只能编译,但是不行,我们可以举个例子试试

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

但以下应该有效

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