Kotlin Primer
Strings
Strings in Kotlin have some really nice enhancements over Java
In-String Expressions
You can evaluate expressions inside Strings, which makes it much simpler than the concatenation
needed in Java.
class Person(
var name: String
)
fun main() {
val person = Person("Scott")
val numberOfChaptersRead = 42
val message = "${person.name} has read $numberOfChaptersRead chapters!"
println(message)
}
Expressions can be included inside ${...}. If the expression is just a simple reference,
such as numberOfChaptersRead, you can usually just prepend $ in front of it, and it will be
evaluated.
Sometimes, even for simple references, you need the full ${...}. For example, if the reference is
followed by a character that can be part of a property name, you need the ${...} to mark where
your actual property name ends.
fun main() {
val term = "fall"
val termMessage =
if (term == "summer")
"Note: Summer terms are held online. "
else
""
val uglyMessageWithExtraSpace =
"Welcome to the class! $termMessage We'll be exploring ..."
val betterLookingMessage =
"Welcome to the class! ${termMessage}We'll be exploring ..."
println(uglyMessageWithExtraSpace)
println(betterLookingMessage)
}
In this example, because we didn't want two spaces when the termMessage was blank, we
either need to append the "$" directly after the "!" or use the full syntax when adjacent to
the "W". Try changing the term to fall to see the difference
Multi-line Strings
Sometimes we need longer Strings that may span multiple lines. While we can use "+" like in
Java to concatenate
fun main() {
val message =
"Hello there.\n" +
"This is a message that spans " +
"multiple lines in the source code."
println(message)
}
The \n is a literal new-line character and splits the output across lines.
We can use a simpler format called a "Multi-line String" (sometimes called "Raw String", surrounded by three quotes on each end
fun main() {
val message = """
Hello there.
This is a message that spans multiple lines in the source code.
"""
println(message)
}
This preserves the line breaks and indentation inside the string. Note that when we run we see a blank line, followed by the text, indented.
You can reduce the indents by the least indented line using
fun main() {
val message = """
Hello there.
This is a message that spans multiple lines in the source code.
This line is indented.
This one is not.
""".trimIndent()
println(message)
}
Or explicitly control the indentation using a margin indicator (| is the default)
fun main() {
val message = """
|Hello there.
|This is a message that spans multiple lines in the source code.
| This line is indented.
|This one is not.
""".trimMargin()
println(message)
}
Note that escape sequences like \n won't work inside multiline strings.