case class T (a:String,b:String)
val x=T("a","b")
// I want to print the member a of x, so the expected value is a. but it doesn't work.
println(s"$x.a")
运行命令,改为打印T(a,b).a
。
scala> case class T (a:String,b:String)
defined class T
scala> val x=T("a","b")
x: T = T(a,b)
scala> println(s"$x.a")
T(a,b).a
答案 0 :(得分:4)
你需要用大括号括起来:
scala> case class T (a:String,b:String)
defined class T
scala> val x=T("a","b")
x: T = T(a,b)
scala> println(s"$x.a")
T(a,b).a
scala> println(s"${x.a}")
a
来自docs:
字符串插值器也可以采用任意表达式。例如:
println(s“1 + 1 = $ {1 + 1}”) 将打印字符串1 + 1 = 2.
可以在$ {}中嵌入任意表达式。
答案 1 :(得分:3)
尝试使用大括号,如下所示,
println(s"${x.a}")