问题
I am new to Scala so feel free to point me in the direction of documentation but I was not able to find an answer to this question in my research.
I am using scala 2.11.8 with Spark2.2 and trying to create a dynamic string containing dateString1_dateString2 (with underscores) using interpolation but having some issues.
val startDt = "20180405"
val endDt = "20180505"
This seems to work:
s"$startDt$endDt"
res62: String = 2018040520180505
But this fails:
s"$startDt_$endDt"
<console>:27: error: not found: value startDt_
s"$startDt_$endDt"
^
I expected this simple workaround with escapes to work but does not produce desired results:
s"$startDt\\_$endDt"
res2: String = 20180405\_20180505
Note that this question differs from Why can't _ be used inside of string interpolation? in that this question is looking to find a workable string interpolation solution while the previous question is much more internals-of-scala focused.
回答1:
You can be explicit using curly braces:
@ s"${startDt}_${endDt}"
res11: String = "20180405_20180505"
Your code:
s"$startDt_$endDt"
fails since startDt_
is a valid identifier, and scala tries to interpolate that non-existant variable.
来源:https://stackoverflow.com/questions/50204130/scala-string-interpolation-with-underscore