是否可以在Scala中为String Interpolation指定类型参数

时间:2017-06-20 21:31:54

标签: scala string-interpolation

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"只会起作用,但如果不能,我想知道是否有比{{1更好的语法允许我指定我期望的类型参数。

1 个答案:

答案 0 :(得分:2)

仅次于编译,但它并没有真正起作用,我们可以尝试例如

implicit class Interpolator(val a: StringContext) extends AnyVal {
    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) extends AnyVal {
    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