Text Templates in Kotlin
Kotlin offers built-in support for creating dynamic content or showing customized output to the user with string templates. We’ll explore how to use string templates in Kotlin to achieve similar functionality as Go’s text/template
package.
import java.io.File
fun main() {
// We can create a new template string with placeholders.
// In Kotlin, we use ${} for variable interpolation.
val t1 = "Value is ${}"
// We can use string templates to insert values
println(t1.format("some text"))
println(t1.format(5))
println(t1.format(listOf("Kotlin", "Java", "Scala", "Groovy")))
// Helper function to create a template
fun createTemplate(template: String): (Any) -> String {
return { value -> template.format(value) }
}
// If the data is an object, we can access its properties
// using the ${} syntax
val t2 = createTemplate("Name: ${name}\n")
data class Person(val name: String)
println(t2(Person("Jane Doe")))
// The same applies to maps
println(t2(mapOf("name" to "Mickey Mouse")))
// Conditional execution can be achieved using if-else expressions
val t3 = createTemplate(
"#{if (it.toString().isNotEmpty())} yes #{else} no #{endif}\n"
.replace("#", "$")
)
println(t3("not empty"))
println(t3(""))
// We can use for loops to iterate over collections
val t4 = createTemplate("Range: ${it.joinToString(" ")}\n")
println(t4(listOf("Kotlin", "Java", "Scala", "Groovy")))
}
// Extension function to replace placeholders in templates
fun String.format(value: Any): String {
return when (value) {
is Iterable<*> -> this.replace("{}", value.joinToString(", ", "[", "]"))
else -> this.replace("{}", value.toString())
}
}
To run the program, save it as TextTemplates.kt
and use kotlinc
to compile and kotlin
to run:
$ kotlinc TextTemplates.kt -include-runtime -d TextTemplates.jar
$ kotlin TextTemplates.jar
Value is some text
Value is 5
Value is [Kotlin, Java, Scala, Groovy]
Name: Jane Doe
Name: Mickey Mouse
yes
no
Range: Kotlin Java Scala Groovy
In this Kotlin example, we’ve used string templates and extension functions to mimic the behavior of Go’s text templates. Kotlin’s string interpolation with ${}
provides a powerful way to create dynamic strings.
The format
extension function allows us to replace placeholders in our template strings with actual values. For collections, we join the elements into a string representation.
Conditional logic is implemented using Kotlin’s if-else expressions within the string template. For loops are handled using Kotlin’s collection methods like joinToString
.
While Kotlin doesn’t have a direct equivalent to Go’s template package, its string interpolation and powerful standard library provide flexible ways to create dynamic content.