In programming languages, a string is a data type that holds characters (textual data) or, basically, text. It can be formed by a sequence of letters, digits, punctuation, and other valid characters.
The most famous string ever in the programming land is the “Hello World”. In Kotlin, strings are placed within double quotes "..."
.
So you can have a String called name
and store the value Aragorn
in it:
val name = "Aragorn"
Remember Kotlin’s type inference I mentioned here, so you don’t actually need to declare the variable type, but if you wanted to, it would look like this:
val name: String = "Aragorn"
The same thing can be done with whole sentences, numbers, etc. So the sentence below is also a valid string:
val learnKolin = "Learning Kotlin is as easy as 123..."
While the sentence above is a big fat lie, it’s still a valid string. As long as the numbers and the ellipses are within the double quotes, they will be interpreted as a string and not as an Int or another number data type. There are some special cases about using specific characters in a string that require a few tweaks, but I will talk about that in a bit.
Convert String into Numbers
Sometimes, you will need to convert data types. You might need to convert a string into an Int or a Long. For example, you might need to ask for the user’s input and will use that in your code.
Let’s say you are working on the RPG Adventure but it contains a certain amount of violence (Aragorn chopping orc’s heads off, for example) and you need to determine the player’s age before they can continue.

The readLine( )
function used here is basically the opposite of println( )
. Instead of printing something to the console, it reads whatever you input in the console and it always returns a String. In the example above, even if you input your age in numbers (Int) the result will be a String.

In this specific case, it would be ok if you are not using the value from the age variable to perform any math, but, let’s imagine a different situation.
Say you are building a Guess the Number game. You will have a variable called result
that will generate a random number between 0 and 100. The user will input their guess and the program will compare the input to the actual result and let the user know if the number they guessed is greater than or less than the correct result. But how can you compare numbers if the readLine ( )
funtion returns a String?
Consider the following code:
fun main() {
val number = 0..100
val correctNumber = number.random()
println("Welcome to the Guess the Number game! \n")
var userGuess: Int
var attempts = 0
while (true) {
println("Please enter a number")
userGuess = readLine()!!.toInt()
when (userGuess.compareTo(correctNumber)) {
-1 -> {
println("$userGuess is too small")
attempts++
}
0 -> {
attempts++
println("Congrats!!! You guessed the right number in $attempts attempts.")
return
}
1 -> {
println("$userGuess is too big")
attempts++
}
}
}
}
And the following output:

If we don’t convert the readLine( ) input into an Int using the toInt( ) function the IDE will return a type mismatch error saying basically that in order for the code to do what we want, which is to compare* the input provided by the user to the correct number, the input needs to be an Int. You can’t compare oranges to apples.

📌 the *compareTo( ) function used here compares an object (let’s call it object A) to another specified object (Object B) for order. It returns zero if this object A is equal to object B, a negative number if it’s less than object B, or a positive number if it’s greater than object B.
Keep in mind that the code above is not fool-proof, but only a simple illustration of one of the many scenarios where you would need to convert a String into an Int.
For example, let’s say the player when asked for a number inputs 2.0 as opposed to 2. As mentioned here, Integers are whole numbers and don’t accept decimal points. So, if the user inputs 2.0 the conversion using .toInt()
won’t be possible and the program will return an error. The string would need to be converted to Float or Double first, and then converted to Int.

In general, it’s a good idea to check/verify if the input received is the expected one to avoid crashes. There are several things you can do to prevent your program to crash when it receives an invalid input. Kotlin has several ways of doing this. You can create a function to validate the input, or you can use a library, etc. But I will leave this to a different post.
String Interpolation
What if you have a string variable and you need to use this variable within another string, how would that work?
There are a couple of ways you can do that and the first one would be using something called string concatenation. Let’s say you have the following variable val characterName = "Aragorn"
and you will use it in several dialogues throughout the game you are building.
So you could do this: println( "Welcome, " + characterName + ". Please, have a seat.")
and you would have the following output in the console:

This is the desired output, however, it’s a bit boring to write the code like this. The IDE suggests converting String Concatenation into a template and this is where Kotlin’s String interpolation comes into play:

Instead of chopping the string into bits so you can add a variable in the middle, you can use the symbol $ to introduce a placeholder to the string transforming it into a template.
📌 String templates are strings that have one (or more) placeholders.
So you can write the same string like this:
println( "Welcome, $characterName. Please, have a seat.")
This is easier to type and read, right? The placeholder will be replaced with the value for that variable at the time the prinln( )
function is called. String interpolation makes the code more concise and, in this case, easier to read.
You can also use String Interpolation to insert an expression into a string (not only another string). The syntax would be a bit different. You need to add curly braces after the $ and add your expression within the curly braces. So println( "Blah Blah ${ your-expression-here} blah blah blah")
This can be really useful if you need to insert the result of a function for example.
Inside the curly braces, Kotlin lets you write any expression you want. Line breaks, comments, if/else expressions, and when expressions are all allowed inside the curly braces.
println( "Blah Blah ${yourFunction(argument)} blah blah blah")
Escaped and Raw String
Kotlin has two types of string literals. But first things first, what is a literal?
It is a notation that represents a fixed value in the code. It is the source code representation of that value. So when you declare a variable and initiate it, you have a literal. In val name = "Charles Darwin"
, “Charles Darwin” is a string literal with the value Charles Darwin (the quotes are not included in the value).
The double quotes are used in a lot of programming languages to determine a string. But what if you want to use double quotes?
For this (and to use other symbols that are used in the language) you can escape the character. How you ask?
Let’s say you want to have a quote within a string. So you haveval quote = " As J.R.R Tolkien once said "Not all those who wander are lost""
If you write the code like this, the compiler will read the second quote, after the word said as if it was the end of the string

So you need to let the compiler know the quote is actually part of the string. For that, you will need to escape the quotation character and this will tell the compiler to treat that as text and not as syntax. To escape a character you can use a backslash \. So the code would look like this:
val quote = " As J.R.R Tolkien once said \"Not all those who wander are lost\""
And as you can see, the IDE stops complaining:

Here’s a list of the Escape sequences you can use:
Escape Sequence | Meaning |
\t | Tab character |
\b | Backspace character |
\n | Newline character |
\r | Carriage return |
\” | Double quotation mark |
\’ | Single quotation mark/apostrophe |
\\ | Backslash |
\$ | Dollar Sign |
\u | Unicode character |
Using escape sequences can get really convoluted when need to escape a lot of characters. Think about the string "\t \"Hi $name\", said the customer. \" Paying \$50 for a burger seems too much\""
Seems like a lot, right? It’s ok when you need to escape one or two characters, but more than that starts to get a bit tricky.
To avoid that, Kotlin has a really nice feature called Raw Strings. They allow you to use special characters without escaping them. Raw strings let you insert newline characters, quotation marks, and other symbols that you would normally need to escape. In fact, raw strings do not support escape sequences at all.
To create a new raw string you can enclose your text with three quotation marks (""" your raw string here """)
So, using a raw string, the very confusing string above would look like this with the exact same result but with all the escaping sequences:
"""
"Hi $name", said the customer "Paying $50 for a burgers seem too much!"
"This is just to illustrate that raw strings respect white spaces as well"
"""
And this is how it would be printed in the console:

One thought on “Strings in Kotlin”