假设我使用任意标识符作为字段名称:
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`"
}
我得到了
error: invalid string interpolation: `$$', `$'ident or `$'BlockExpr expected
override def toString() = s"$`type`"
答案 0 :(得分:2)
我认为我找到了解决方案,必须将反引号标识符放在大括号中:
object A {
val `type` = "x"
override def toString() = s"${`type`}"
}