带下划线的Scala字符串插值 [英] Scala String Interpolation with Underscore
问题描述
我对Scala还是陌生的,因此可以随时指出文档的方向,但是我在研究中找不到该问题的答案.
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.
我正在使用带有Spark2.2的 scala 2.11.8 ,并尝试使用内插法创建一个包含dateString1_dateString2(带下划线)的动态字符串,但是存在一些问题.
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"
这似乎可行:
s"$startDt$endDt"
res62: String = 2018040520180505
但这失败了:
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.
推荐答案
您可以使用花括号将其明确显示:
You can be explicit using curly braces:
@ s"${startDt}_${endDt}"
res11: String = "20180405_20180505"
您的代码:
s"$startDt_$endDt"
失败,因为startDt_
是有效的标识符,并且scala尝试对不存在的变量进行插值.
fails since startDt_
is a valid identifier, and scala tries to interpolate that non-existant variable.
这篇关于带下划线的Scala字符串插值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!