gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 05:20:24 26 4
gpt4 key购买 nike

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

关于scala - 是否可以在 Scala 中为字符串插值指定类型参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44663377/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com