Search code examples
javastringkotlinjointrim

Insert Kotlins ${ } expression while splitting String() in order to add dynamic data after the split


Here is an example of a String:

val message = "Customer name is $name saved on $date"

I needed to find every instance of $variable within the string message and replace it with querySnapShot.get(variable) and that has been answered here Previous Answer. querySnapShot here just contains data from within Firestore listener.

Here is the working Kotlin code:

val message = "Customer name is $name saved on $date"

    val arr = message.split(" ").toTypedArray()

    for (i in 0 until arr.size) {
        val s = arr[i]
        if (s.contains("$")) {
            arr[i] = "+ querySnapshot.get(" + "\"" + s.substring(1) + "\"" + ")"
        }
    }

    Log.d("Mate", java.lang.String.join(" ", *arr))

which prints:

customer name is querySnapShot.get("name") saved on querySnapshot.get("data)

literally as it is.

QUESTION: How can I add Kotlin's expression ${} correctly while splitting and joining in order for it to treat querySnapshot.get("variable") as an expression that captures and returns dynamic data after joining? And not just a mere String.


Solution

  • Write

    arr[i] = querySnapshot.get(s.substring(1))
    

    The solution isn't to try to use Kotlin string templating, it's to stop putting your own code in strings when you want to run it instead!