Scala 内插字符串中的反引号标识符
假设我使用任意标识符作为字段名:Scala 内插字符串中的反引号标识符,scala,Scala,假设我使用任意标识符作为字段名: object A { val `type` = "x" } 如何在插值字符串中引用它 我试过了 object A { val `type` = "x" override def toString() = s"$type" } 但出现了一个编译器错误: error: error in interpolated string: identifier or block expected override def toString() = s"$t
object A { val `type` = "x" }
如何在插值字符串中引用它
我试过了
object A {
val `type` = "x"
override def toString() = s"$type"
}
但出现了一个编译器错误:
error: error in interpolated string: identifier or block expected
override def toString() = s"$type"
如果我尝试
object A {
val `type` = "x"
override def toString() = s"$`type`"
}
我明白了
我想我找到了解决方案,必须将后引号标识符放在大括号中:
object A {
val `type` = "x"
override def toString() = s"${`type`}"
}
有人建议在插值中使用任意标识符,但没有出现这种情况。文档确实说
s“$id”
扩展为s“${id}”
所以s“$type”
不能正确工作。但是错误信息是可怕的。
object A {
val `type` = "x"
override def toString() = s"${`type`}"
}