0
0
Kotlinprogramming~5 mins

String templates and interpolation in Kotlin - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a string template in Kotlin?
A string template in Kotlin is a way to include variables or expressions inside a string by using the $ symbol before the variable name or ${} for expressions.
Click to reveal answer
beginner
How do you include a variable name inside a string using Kotlin string templates?
You write the string like this: "Hello, $name!". Kotlin replaces $name with the value of the variable name.
Click to reveal answer
beginner
How do you include an expression like 2 + 3 inside a Kotlin string template?
You use curly braces around the expression: "The sum is ${2 + 3}". Kotlin calculates the expression and inserts the result.
Click to reveal answer
intermediate
What happens if you want to include a literal dollar sign $ in a Kotlin string template?
You escape it by using \$. For example, "Price is \$5" will show Price is $5.
Click to reveal answer
intermediate
Can you use string templates with multiline strings in Kotlin?
Yes! You can use string templates inside triple-quoted strings """...""". Variables and expressions inside $ or ${} will be replaced as usual.
Click to reveal answer
How do you insert the value of a variable age into a Kotlin string?
A"I am $age years old"
B"I am age years old"
C"I am ${age}"
D"I am ${age years old}"
What is the output of: val x = 5; println("x + 2 = ${x + 2}")?
Ax + 2 = 5 + 2
Bx + 2 = x + 2
Cx + 2 = ${x + 2}
Dx + 2 = 7
How do you write a literal dollar sign in a Kotlin string template?
A$$
B\$
C$
D\\$
Which of these is a valid Kotlin string template expression?
A"Hello, ${user.name!}"
B"Hello, $user.name!"
C"Hello, ${user.name}!"
D"Hello, $user.name!" with quotes
Can you use string templates inside triple-quoted strings in Kotlin?
AYes, variables and expressions are replaced.
BNo, string templates don't work in triple quotes.
COnly variables work, not expressions.
DOnly expressions work, not variables.
Explain how to use string templates in Kotlin to include variables and expressions inside strings.
Think about how you write a sentence with a variable inside.
You got /4 concepts.
    Describe how to include a literal dollar sign character in a Kotlin string that uses string templates.
    Remember that $ is special in string templates.
    You got /3 concepts.