
上QQ阅读APP看书,第一时间看更新
How to do it...
In the following steps, we will learn how to use String templates:
- In Kotlin, the template expression starts with a $ sign.
- The syntax of string templates is as follows:
$variableName
Alternatively, it is this:
${expression}
- Let's check out a few examples:
- Consider the example of a String template with variable:
fun main(args: Array<String>) {
val foo = 5;
val myString = "foo = $foo"
println(myString)
}
The output of the preceding code will be foo = 5.
- Consider the example of a String template with expression:
fun main(arr: Array<String>){
val lang = "Kotlin"
val str = "The word Kotlin has ${lang.length} characters."
println(str)
}
- Consider the example of a String template with raw string:
- Raw string: A string consisting of newlines without writing \n and arbitrary string. It's a raw string and is placed in triple quotes ("""):
fun main(args: Array<String>) {
val a = 5
val b = 6
val myString = """
${if (a > b) a else b}
"""
println("Bigger number is: ${myString.trimMargin()}")
}
When you run the program, the output will be Bigger number is: 6.