In software programming, variables hold data and have a type. In Kotlin, variables can be read-only or mutable. In this demo, you’ll see how to initialize and work with variables in Kotlin. Later in this video, you’ll learn about code comments too. Start a new Kotlin Playground session or choose your preferred Kotlin environment to get started.
Using Variables
A variable holds data and has a name. In Kotlin, this is how variables are declared:
var day = "Monday"
val week = 2
It begins with the keyword var or val, followed by the name of the variable, an equals operator, and finally, the value to be assigned to the variable.
You may initialize a variable without assigning data by introducing lateinit. Declare a lateinit above the main function and assign a value to it as before:
lateinit var day : String
fun main(args: Array<String>) {
day = "Monday"
}
Mutable and Read-only Variables
To update a variable, it needs to be mutable. The previous example is mutable since it’s a var. To update it, remove the keyword and assign a different value of the same type:
fun main(args: Array<String>) {
day = "Monday"
println(day)
day = "Tuesday"
println(day)
}
When you print the variable day after each assignment, you realize it holds different values at different points in the program.
To make it read-only, use val in place of var:
val day = "Monday"
Attempting to update an immutable variable will result in an error.
val day = "Monday"
day = "Tuesday" // Error
Run the program. You get an error that says, Val cannot be reassigned. You have to change val day to var day to be able to update it.
Basic Data Types
Basic types in Kotlin include integers, floating-point numbers, booleans, characters and strings.
Int
Integers represent numbers in Kotlin between -2,147,483,648 (-2^31^) and 2,147,483,647 (-2^31^ - 1). Here’s an example of an integer data type:
val amount = 100
println(amount::class.java.simpleName)
It displays int when you run the code.
Long
If a value exceeds the limit for an Integer, it becomes a Long. Longs are also numeric values but have a higher capacity than Ints. Here’s an example of a Long:
val amount = 100L
println(amount::class.java.simpleName)
The L at the end of the number makes this value a Long. There are other ways of defining Longs in Kotlin.
Floating-point
Floating-point types are numbers with decimals or fractions. Single-precision or decimal numbers holding 32 bits of data, are assigned the Floattype when creating variables. To initialize a floating point number explicitly, append an f to the number:
val amount = 100f
println(amount::class.java.simpleName)
In the console, the type displayed is float.
Double
For higher or double-precision numeric data, use the Double class type. Double stores 64 bits of numeric data. To initialize a Double, use precision or a decimal point.”
val amount = 100.0
println(amount::class.java.simpleName)
Did you notice that the output of the Float, 100f and the Double, 100.0, was the same? It was 100.0. So, how do you know if 100.0 is a Float or a Double? We’ll cover that in the next lesson!
Kotlin has this neat little feature that allows you to write long figures in a readable manner. If you had a figure in the hundreds of thousands or in the millions or more, you could separate every thousand with an underscore, _:
val amount = 12_000_000_000
println(amount)
From the console, you can tell the amount is twelve billion.
Boolean
The Boolean data type can be only one of two types: true or false. This makes it suitable for representing data that can only be in two states.
In the next example, the isWeekday variable tells whether it’s a weekday or not whiles isHoliday tells whether it’s a holiday or not:
val isWeekday = true
val isHoliday = false
Character
Characters represent single-character symbols and numbers. They’re instantiated using single quotes ' and must contain one character or two if it’s a special character:
val grade = 'A'
An example of a special character is the new line character. \n creates a new line. Special characters are preceded by a \ and have distinct meanings depending on the character(s) that follow the \.
val newLine = '\n'
print("Monday")
print(newLine)
print("Tuesday")
Execute this code. The newLine character moves the print cursor to the next line. Remove the print statement for newLine and the results are printed on one line.
String
Strings represent text. Strings are a sequence of characters put together and are initialized with double quotes ". They may or may not contain any characters.
There are two types of string literals in Kotlin:
-
Escaped strings: These are strings that contain the escape character
\. This is the same as the special characters you saw earlier. - Multiline strings: Multiline strings begin with three double quotes instead of two. They contain newlines and don’t use special characters or escaped strings.
For escaped strings, add the following closing message to your program at the bottom of the main function:
val message = "End of the program!\nSee you next week."
println(message)
Run the program. The text that follows \n appears on a new line in the console:
Here’s how the same message can be written as a multiline string:
val message = """
End of the program!
See you next week.
"""
println(message)
Run the program. The text appears exactly as written.
Next, you’ll see how comments are written, and how to use them in Kotlin.
Comments
Comments are a way to leave notes in your code. Comments are not interpreted as part of the code and can be short or long. For short comments, write your notes after // followed by a space. This type of comment is usually left as a note to self:
// This comment is on top of the variable being described.
const val WEEKLY_INTEREST = 100 // This comment is beside the variable being described.
This is known as a single-line or end-of-line comment. Or you could make your comment span multiple lines by writing the text in between /* and */. This is known as a block comment:
/** This is known
as a block comment. */
const val WEEKLY_INTEREST = 100
For even longer comments, put your text in between /** and */. This is known as documentation comments. They’re used by documentation tools to create documents from the comment text. Try the following:
/** This comment is a longer comment giving further information about the variable. */
const val WEEKLY_INTEREST = 100
If it spans several lines, which is the ideal case, new lines should start subsequent lines with a * followed by a space:
/**
* This comment is longer.
* It has more information.
*/
const val WEEKLY_INTEREST = 100
Kotlin comment blocks can begin with a single slash and asterisk, /*, and do not need to have astericks at the beginning of each line. Documentation tools will not create documentation from comment blocks beginning with /*:
/*
This comment is longer.
It has more information.
This is a valid comment block, but cannot be used with automatic document creation tools.
*/
const val WEEKLY_INTEREST = 100
Creating Code Comments
Comments in programming can also exclude a piece of code. Comments aren’t interpreted by the compiler, so they won’t have any effect on the output of the program. Consider the following example:
// const val WEEKLY_INTEREST = 100 /* This code is said to be commented out.*/
That’s all for this demo.