简体   繁体   中英

Scala String Interpolation with Underscore

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM