1

I have two strings:

val s1: String = "aaa/$Y/$m/aaa_$Y$m$d" // this one has all three variables
val s2: String = "aaa/$Y/$m" // this one has only two variables

val myStrings: Seq[String] = Seq(s1, s2)

val myStringsUpdated: Seq[String] = myStrings.map(s => ???)

Can I inject Y, m, d values into s1, s2 dynamically so I get myStringsUpdated sequence?

3
  • 2
    This does not answer the question. But if m / d / Y comes from a date object. You could use .format method with your string pattern Commented Jun 29, 2021 at 16:42
  • so if year = dtObject.year, month = dtObject.month and day = dtObject.day then would it be "aaa/$Y/$m/aaa_$Y$m$d".format(year, month, year, month, day) ? Commented Jun 30, 2021 at 6:21
  • 1
    Something like this should do the trick: scastie.scala-lang.org/1qNWgX94TPiZiEvvcZU6jw Everything between single quotes doesn't get interpreted by the date time formatter Commented Jun 30, 2021 at 7:31

2 Answers 2

4

As Tim already mentioned interpolation is done at compile-time, so you can't use it directly, but you could do a simple trick and wrap it into function:

//instead of plain interpolated string we've got function returning interpolated string
def s1(Y: String, m: String, d: String): String = s"aaa/$Y/$m/aaa_$Y$m$d" 
def s2(Y: String, m: String, d: String): String = s"aaa/$Y/$m" 

val myStrings: Seq[(String, String, String) => String] = Seq(s1, s2)

//you inject value by just applying function
val myStringsUpdated = myStrings.map(_.apply("1999", "11", "01"))

println(myStringsUpdated) //List(aaa/1999/11/aaa_19991101, aaa/1999/11)
Sign up to request clarification or add additional context in comments.

Comments

3

String interpolation is done at compile time so it has to know which variables are needed and where they will go. But it is just a shorthand for concatenating static String values and the results of toString calls, so it should be reasonably straightforward to build the string you want dynamically.

If you provide more details of the conditions/transformations then there are probably some clean solutions e.g. using Option.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.