Kotlin
Kotlin
What is Kotlin?
Kotlin is a modern, trending programming language that was released in
2016 by JetBrains.
It has become very popular since it is compatible with Java (one of the most
popular programming languages out there), which means that Java code
(and libraries) can be used in Kotlin programs.
Kotlin IDE
The easiest way to get started with Kotlin, is to use an IDE.
We will use IntelliJ (developed by the same people that created Kotlin) which
is free to download from https://www.jetbrains.com/idea/download/.
Kotlin Syntax
Example
fun main() {
println("Hello World")
Example explained
The fun keyword is used to declare a function. A function is a block of code
designed to perform a particular task. In the example above, it declares
the main() function.
The main() function is something you will see in every Kotlin program. This
function is used to execute code. Any code inside the main() function's curly
brackets {} will be executed.
For example, the println() function is inside the main() function, meaning
that this will be executed. The println() function is used to output/print
text, and in our example it will output "Hello World".
fun main() {
println("Hello World")
}
You can add as many println() functions as you want. Note that it will add
a new line for each function:
Example
fun main() {
println("Hello World!")
println("It is awesome!")
Example
fun main() {
println(3 + 3)
Example
fun main() {
print("It is awesome!")
Note that we have added a space character to create a space between the
sentences.
Kotlin Comments
Kotlin Comments
Comments can be used to explain Kotlin code, and to make it more readable.
It can also be used to prevent execution when testing alternative code.
Single-line Comments
Single-line comments starts with two forward slashes (//).
Any text between // and the end of the line is ignored by Kotlin (will not be
executed).
Example
// This is a comment
println("Hello World")
Example
Multi-line Comments
Multi-line comments start with /* and ends with */.
println("Hello World")
Kotlin Variables
Kotlin Variables
Variables are containers for storing data values.
To create a variable, use var or val, and assign a value to it with the equal
sign (=):
Syntax
Example
The difference between var and val is that variables declared with
the var keyword can be changed/modified, while val variables cannot.
Variable Type
Unlike many other programming languages, variables in Kotlin do not need
to be declared with a specified type (like "String" for text or "Int" for
numbers, if you are familiar with those).
To create a variable in Kotlin that should store text and another that should
store a number, look at the following example:
Example
Example
println(name)
println(birthyear)
You can also declare a variable without assigning the value, and assign the
value later. However, this is only possible when you specify the type:
Example
name = "John"
println(name)
Example
var name
name = "John"
println(name)
Notes on val
When you create a variable with the val keyword, the value cannot be
changed/reassigned.
The following example will generate an error:
Example
println(name)
When using var, you can change the value whenever you want:
Example
name = "Robert"
println(name)
The val keyword is useful when you want a variable to always store the
same value, like PI (3.14159...):
Example
val pi = 3.14159265359
println(pi)
Display Variables
Like you have seen with the examples above, the println() method is often
used to display variables.
Example
You can also use the + character to add a variable to another variable:
Example
println(fullName)
Example
val x = 5
val y = 6
Variable Names
A variable can have a short name (like x and y) or more descriptive names
(age, sum, totalVolume).
camelCase variables
You might notice that we used firstName and lastName as variable names
in the example above, instead of firstname and lastname. This is called
"camelCase", and it is considered as good practice as it makes it easier to
read when you have a variable name with different words in it, for example
"myFavoriteFood", "rateActionMovies" etc.
Kotlin Data Types
Kotlin Data Types
In Kotlin, the type of a variable is decided by its value:
Example
However, you learned from the previous chapter that it is possible to specify
the type if you want:
Example
Sometimes you have to specify the type, and often you don't. Anyhow, it is
good to know what the different types represent.
You will learn more about when you need to specify the type later.
Numbers
Characters
Booleans
Strings
Arrays
Numbers
Number types are divided into two groups:
If you don't specify the type for a numeric variable, it is most often returned
as Int for whole numbers and Double for floating point numbers.
Integer Types
Byte
The Byte data type can store whole numbers from -128 to 127. This can be
used instead of Int or other integer types to save memory when you are
certain that the value will be within -128 and 127:
Example
println(myNum)
Short
The Short data type can store whole numbers from -32768 to 32767:
Example
println(myNum)
Int
The Int data type can store whole numbers from -2147483648 to
2147483647:
Example
println(myNum)
Long
The Long data type can store whole numbers from -9223372036854775807
to 9223372036854775807. This is used when Int is not large enough to
store the value. Optionally, you can end the value with an "L":
Example
println(myNum)
Example
The Float and Double data types can store fractional numbers:
Float Example
println(myNum)
Double Example
Also note that you should end the value of a Float type with an "F".
Booleans
The Boolean data type and can only take the values true or false:
Example
Characters
The Char data type is used to store a single character. A char value must be
surrounded by single quotes, like 'A' or 'c':
Example
println(myGrade)
Unlike Java, you cannot use ASCII values to display certain characters. The
value 66 would output a "B" in Java, but will generate an error in Kotlin:
Example
println(myLetter) // Error
Strings
The String data type is used to store a sequence of characters (text). String
values must be surrounded by double quotes:
Example
println(myText)
Arrays
Arrays are used to store multiple values in a single variable, instead of
declaring separate variables for each value.
Type Conversion
Type conversion is when you convert the value of one data type to another
type.
Example
val x: Int = 5
val y: Long = x
To convert a numeric data type to another type, you must use one of the
following
functions: toByte(), toShort(), toInt(), toLong(), toFloat(), toDouble() o
r toChar():
Example
val x: Int = 5
println(y)
Kotlin Input
Kotlin standard input is the basic operation performed to flow byte streams
from input device such as Keyboard to the main memory of the system.
You can take input from user with the help of the following function:
readline() method
Scanner class
Output:
Enter text: Hello, Geeks! You are learning how to take input using
readline()
You entered: Hello, Geeks! You are learning how to take input using
readline()
fun main() {
Output
Enter an integer: 123
You entered: 123
Enter a float value: 40.45
You entered: 40.45
Enter a boolean: true
You entered: true
Output:
Enter an Integer value: 123
You entered: 123
Enter a double value: 22.22222
You entered: 22.22222
Kotlin Operators
Kotlin Operators
Operators are used to perform operations on variables and values.
100 + 50
In the example below, the numbers 100 and 50 are operands, and
the + sign is an operator:
Example
var x = 100 + 50
Although the + operator is often used to add together two values, like in the
example above, it can also be used to add together a variable and a value, or
a variable and a variable:
Example
Kotl
in
divi
des
the
ope
rat
ors
into
the
foll
owi
ng
gro
ups
:
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Arithmetic Operators
Arithmetic operators are used to perform common mathematical operations.
+ Addition Adds together two values x+y
In the example below, we use the assignment operator (=) to assign the
value 10 to a variable called x:
Example
var x = 10
The addition assignment operator (+=) adds a value to a variable:
Example
var x = 10
x += 5
= x=5 x=5
+= x += 3 x=x+3
-= x -= 3 x=x-3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
!= Not equal x != y
Kotlin Strings
Strings are used for storing text.
Example
Unlike Java, you do not have to specify that the variable should be a String.
Kotlin is smart enough to understand that the greeting variable in the
example above is a String because of the double quotes.
However, just like with other data types, you can specify the type if you
insist:
Example
Note: If you want to create a String without assigning the value (and assign
the value later), you must specify the type while declaring the variable:
Example
This works fine:
println(name)
Example
This will generate an error:
var name
name = "John"
println(name)
String Concatenation
The + operator can be used between strings to add them together to make a
new string. This is called concatenation:
Example
Note that we have added an empty text (" ") to create a space between
firstName and lastName on print.
String Templates/Interpolation
Instead of concatenation, you can also use "string templates", which is an
easy way to add variables and expressions inside a string.
Example
Kotlin Booleans
Very often, in programming, you will need a data type that can only have
one of two values, like:
YES / NO
ON / OFF
TRUE / FALSE
For this, Kotlin has a Boolean data type, which can take the
values true or false.
Boolean Values
A boolean type can be declared with the Boolean keyword and can only take
the values true or false:
Example
Just like you have learned with other data types, the example above can also
be written without specifying the type, as Kotlin is smart enough to
understand that the variables are Booleans:
Example
You can use a comparison operator, such as the greater than (>) operator
to find out if an expression (or a variable) is true:
Example
val x = 10
val y = 9
println(x > y) // Returns true, because 10 is greater than 9
Example
Example
val x = 10;
Example
The Boolean value of an expression is the basis for all Kotlin comparisons and
conditions.
You can use these conditions to perform different actions for different
decisions.
Kotlin if
Use if to specify a block of code to be executed if a condition is true.
Syntax
if (condition) {
Note that if is in lowercase letters. Uppercase letters (If or IF) will generate
an error.
In the example below, we test two values to find out if 20 is greater than 18.
If the condition is true, print some text:
Example
val x = 20
val y = 18
if (x > y) {
Example explained
Kotlin else
Use else to specify a block of code to be executed if the condition is false.
Syntax
if (condition) {
} else {
Example
val time = 20
println("Good day.")
} else {
println("Good evening.")
}
// Outputs "Good evening."
Example explained
In the example above, time (20) is greater than 18, so the condition
is false, so we move on to the else condition and print to the screen "Good
evening". If the time was less than 18, the program would print "Good day".
Kotlin else if
Use else if to specify a new condition if the first condition is false.
Syntax
if (condition1) {
} else if (condition2) {
} else {
Example
val time = 22
println("Good morning.")
println("Good day.")
} else {
println("Good evening.")
}
// Outputs "Good evening."
Example explained
In the example above, time (22) is greater than 10, so the first
condition is false. The next condition, in the else if statement, is also false,
so we move on to the else condition since condition1 and condition2 is
both false - and print to the screen "Good evening".
However, if the time was 14, our program would print "Good day."
Example
val time = 20
"Good day."
} else {
"Good evening."
println(greeting)
Note: You can ommit the curly braces {} when if has only one statement:
Example
fun main() {
val time = 20
val greeting = if (time < 18) "Good day." else "Good evening."
println(greeting)
}
Tip: This example is similar to the "ternary operator" (short hand if...else) in
Java.
Kotlin when
Instead of writing many if..else expressions, you can use
the when expression, which is much easier to read.
Example
Use the weekday number to calculate the weekday name:
val day = 4
1 -> "Monday"
2 -> "Tuesday"
3 -> "Wednesday"
4 -> "Thursday"
5 -> "Friday"
6 -> "Saturday"
7 -> "Sunday"
println(result)