2

Can i transform string in template expression or lambda expression in kotlin?

val tm = "x = $"+"x"
val fn: (x: String) -> String = { it -> tm}
val str = fn("This is X!!!")

Need to get

x = This is X!!!

Why?: You can receive templates, for example, from the database PS: or your suggestions

1
  • No: the Kotlin string templates are transformed at compile-time into simple concatenation. You need different tools for string templates at runtime. Commented Aug 21, 2017 at 14:39

1 Answer 1

2

Kotlin templates are evaluated at compile time - so this won't work.

You should use a 3rd party template engine.

Freemarker is such an engine with a format very similar to Kotlin's own templating format:

val tm = "x = \${x}"

fun fn (x: String) : String {
    val t = Template("name", StringReader(tm), Configuration(Configuration.VERSION_2_3_26))
    val out = StringWriter()
    t.process(mapOf("x" to x) ,out)
    return out.toString()
}

println (fn("This is X!!!")) // x = This is X!!!

Two notes:

  • You won't be able to use "$x" on freeMarker, only "${x}"
  • $ sign can be escaped in a Kotlin string using \$
Sign up to request clarification or add additional context in comments.

2 Comments

When will we use it instead of String.format()? They look similar.
String.format() is an alias for java.lang.String.format(format, *args) - it is useful, but it is different. here.

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.