3

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.

user9074332
  • 2,336
  • 2
  • 23
  • 39
  • 1
    Possible duplicate of [Why can't \_ be used inside of string interpolation?](https://stackoverflow.com/questions/19895467/why-cant-be-used-inside-of-string-interpolation) – Raman Mishra May 06 '18 at 20:17
  • Did you try to use raw interpolation? – Raman Mishra May 06 '18 at 20:21
  • 4
    s"${startDt}_${endDt}" – Leo C May 06 '18 at 20:22
  • 1
    @RamanMishra I don't think it is a duplicate of that question. That question is about using the _ anonymous placeholder parameter. This is about smashing _ at the end of a $ variable and looking up another. – Andy Hayden May 06 '18 at 22:12

1 Answers1

8

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.

Andy Hayden
  • 359,921
  • 101
  • 625
  • 535
  • Yes, this does compile but does not produce the required results: `val startDt_ = "20180405" val endDt = "20180505" s"$startDt_$endDt" res13: String = 2018040520180505` – user9074332 May 07 '18 at 01:31
  • @user9074332 yes, because in that case, the `_` is part of the variable name, but you want a literal `_` character in your string. – puhlen May 07 '18 at 01:58
  • @user9074332 my point was "that's what the error means" (it's looking up the variable `startDt_`). :) – Andy Hayden May 07 '18 at 02:58