Instruction 2

Strings

Strings are arguably the most used data type in software programs. Strings represent text. In Kotlin, Strings store a sequence of characters which are declared in double quotes: "Hippopotamus". Since a string is a sequence, you can also inspect each character by iterating over it. Add the following code to your main function. You’ll print every character that forms part of the string as you loop over it:

fun main() {
   val animal = "Hippopotamus"

   for (character in animal) {
      println(character)
   }
}

It prints each character in the string:

H
i
p
p
o
p
o
t
a
m
u
s

Strings are final by default. This means that once a String is created, it can’t be altered. When you update a string, a new String representing the updated value is created and assigned to the variable. This also means that the more Strings you update or create, the more memory your program takes.

By the following code, you’ll have both “Hippopotamus” and “Giraffe” in memory until all such unused data is cleared up by the system later on.

val animal = "Hippopotamus"
animal = "Giraffe"

The String methods never change the data they work on. They always create a new one:

fun main() {
   val animal = "Hippopotamus"
   println(animal.uppercase()) // A new string is created and returned to the println() function
   println(animal) // The string remains the same
}

Run the code, and it displays animal in capital letters and then as assigned, Hippopotamus:

HIPPOPOTAMUS
Hippopotamus

Using String Concatenation

To create a string, you can use a method known as String concatenation. This is where you use the+operator or its equivalent `plus() function to edit a new value of a String.

In the code below, the word “Hippopotamus” is created from the short names “Hippo” and “potamus”:

fun main() {
   val fullName = "Hippo" + "potamus"
   println(fullName) // A new string is created from the two strings.
}

Or you could do it with variables:

fun main() {
   val firstName = "Mountain"
   val lastName = "Tiger"
   val fullName = firstName + " " + lastName

   println(fullName) // A new string is created from the two variables and the string literal with a space
}

Note: Strings are final, meaning immutable. They can’t change. Every modification creates a new String instead of modifying the original. There are other efficient methods for creating a String. These include the buildString inline function, the joinToString function, and the StringBuilder and StringBuffer methods.

String Templates and Interpolation

Kotlin has a special feature that evaluates code within a String. After evaluation, Kotlin converts the result to a string if it isn’t one already. It then concatenates the evaluation result with the rest of the string. The result is added at the original location of the expression in the String literal. This convenient conversion reduces the code required to update and use a String.

To have Kotlin evaluate an expression within a string, start the expression with $. The following piece of code evaluates variables within a String:

fun main() {
   val isCorrect = true
   val tigerSpecies = 9
   val animal = "Tigers"

   println("That is $isCorrect. There are $tigerSpecies species of $animal") // Notice how different types of data are evaluated and converted into a String
}

Run the program, and take note of how the variables were evaluated, converted into a String, and concatenated in place:

That is true. There are 9 species of Tigers

After the $, you can follow it up with {, the expression, and close it with }. This is especially useful when the expression contains more than a single item. Modify the previous example to include the curly braces with longer expressions:

fun main() {
   val tigerSpecies = 9
   val animal = "Tigers"

   println("That is ${tigerSpecies == 9}. There are $tigerSpecies species of $animal") // The expression in curly braces evaluates to `true`
}

To use the literal $ symbol in such a case, you can escape it with a backslash \:

fun main() {
   val amount = 100_000_000
   println("Gold is worth more than \$$amount")
}

In a multiline string, backlash escaping is not allowed. You instead have to put the character to simply add the character or put it in single quotes in between the curly braces and the $ sign. See both methods used in the code below:

fun main() {
   val amount = 25

   val chat = """
      Ann: How much does this book cost?
      Bryan: This book costs $${amount}.
      And you get a discount of ${'$'}9.99
   """

   println(chat)
}

Run the program. You can see how the multiline chat String is formatted:

      Ann: How much does this book cost?
      Bryan: This book costs $25.
      And you get a discount of $9.99

Again, you could use longer expressions within the curly braces and even spread them on multiple lines when using a multiline string:

fun main() {
   val lowest = 45
   val cash = 200
   val books = 20

   val chat = """
      Ann: With $$cash how many books can I afford?
      Bryan: ${ if (cash > lowest) 20 else 10 } books.
      Ann: ${
          if (books > 10) "Awesome!"
          else "That's OK!"
         }
   """

println(chat)
}

Run the program. You can see how the multiline curly braces change chat:

      Ann: With $200 how many books can I afford?
      Bryan: 20 books.
      Ann: Awesome!
See forum comments
Download course materials from Github
Previous: Instruction 1 Next: Demo