Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Create an String dynamically based on parameters

I’m parametrizing a query in Scala.

I have an array of strings with column names named colNames.

I want to create an string where for each name of the string the output is A.colName = B.colName and then join all the items in the array putting an " AND " string between each item.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Example of input

val colNames = Array("colName1","colName2")
val table1 = "A"
val table2 = "B"

Example of the desired output

"A.colName1 = B.colName1 AND A.colName2 = B.colName2"

In a non FP language I would do that with a for loop, but I don’t know how to do it in Scala in a functional way.

>Solution :

You can use the map and mkString methods on Array:

scala> colNames map { colName => s"${table1}.${colName} = ${table2}.${colName}" } mkString " AND "
val res0: String = A.colName1 = B.colName1 AND A.colName2 = B.colName2
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading