Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use dynamic string substitution in Kotlin?

I'm looking for a Kotlin way to do a dynamic values substitution into a string. It is clear how to implement it, just want to check if there is something similar in standard library.

Could you help me to find a function which given template and data map returns a resulting string with all template keys replaced with their values?

fun format(template: String, data: Map<String, Any>): String { /* magic */ }

format("${a} ${b} ${a}", mapOf("a" to "Home", "b" to "Sweet))   // -> "Home Sweet Home"
like image 359
diziaq Avatar asked Nov 20 '25 12:11

diziaq


1 Answers

fun format(template: String, data: Map<String, String>): String {
  var retval = template
  data.forEach { dataEntry ->
    retval = retval.replace("\${" + dataEntry.key + "}", dataEntry.value)
  }
  return retval
}

// The $ signs in the template string need to be escaped to prevent
// string interpolation
format("\${a} \${b} \${a}", mapOf("a" to "Home", "b" to "Sweet"))
like image 75
lukas.j Avatar answered Nov 23 '25 09:11

lukas.j



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!