Strings, characters and templates
Strings, characters and templates
A report sentence combines a student name with a score. Kotlin string templates insert variables using a dollar sign and expressions using dollar-brace syntax. Char describes one UTF-16 code unit, whereas String holds a sequence of code units on the JVM.
What you’ll learn
- Insert values and expressions into a string template.
- Distinguish UTF-16 length from visible characters.
Strings, characters and templates in the example
Stored values
A report sentence combines a student name with a score.
Stored valuesTemplate expression
Double quotes form a String and single quotes form a Char.
Template expressionFormatted text
The template computes score + 5 before formatting, so the message contains 85.
Formatted text
Understand strings, characters and templates
Double quotes form a String and single quotes form a Char. Templates format an expression’s value; they do not evaluate arbitrary text as source code. JVM string length measures UTF-16 code units, which can differ from the number of visible Unicode characters.
Follow strings, characters and templates
Save the complete source as Main.kt and use the Kotlin/JVM environment. No separate input file is needed.
Kotlin/JVM · complete program
fun main() {
val name = "Diya"
val score = 80
println("$name scored ${score + 5}")
println("😀".length)
}Expected output
Diya scored 85
2Follow the execution
The template computes score + 5 before formatting, so the message contains 85. The emoji length is two UTF-16 code units on the JVM, not two visible faces. This is a representation boundary, not an error in the text.
Try this in the Kotlin compiler by pasting the complete program.
Practice: Strings, characters and templates
Your task: Does the displayed bonus change the stored score?
Kotlin/JVM · complete program
fun main() {
val name = "Diya"
val score = 80
println("$name scored ${score + 5}")
println("😀".length)
}Worked answer
No. The expression calculates a value for the message without assigning it back. Score remains 80.
Strings, characters and templates: the important boundary
Text indexes and length are not display-width measures. Use appropriate Unicode-aware APIs for user-visible segmentation, and specify encodings for files. Raw triple-quoted strings handle multiline source but still have template rules.
Check your understanding
Strings, characters and templates: what to keep in mind
No. The expression calculates a value for the message without assigning it back. Score remains 80. Text indexes and length are not display-width measures.
Further reading: official Kotlin documentation for this topic.
Reaching the recap and completing the quizzes are separate milestones.