Kotlin Online Tutorial

Kotlin

Kotlin is a modern, trending programming language.

Kotlin is easy to learn, especially if you already know Java (it is 100% compatible with Java).

Kotlin is used to develop Android apps, server side apps, and much more.

funmain(){

println(“Hello World”)

}

 

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 is used for:

  • Mobile applications (specially Android apps)
  • Web development
  • Server side applications
  • Data science

Why Use Kotlin?

  • Kotlin is fully compatible with Java
  • Kotlin works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc.)
  • Kotlin is concise and safe
  • Kotlin is easy to learn, especially if you already know Java
  • Kotlin is free to use
  • Big community/support

Main.kt

funmain(){

println(“Hello World”)

}

 

Kotlin Syntax

In the previous chapter, we created a Kotlin file called Main.kt, and we used the following code to print “Hello World” to the screen:

funmain(){

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”.

Kotlin Output (Print)

The println() function is used to output values/print text:

funmain(){

println(“Hello World”)

}

 

You can add as many println() functions as you want. Note that it will add a new line for each function:

funmain(){

println(“Hello World!”)

println(“I am learning Kotlin.”)

println(“It is awesome!”)

}

 

You can also print numbers, and perform mathematical calculations:

funmain(){

println(3+3)

}

 

The print() function

There is also a print() function, which is similar to println(). The only difference is that it does not insert a new line at the end of the output:

funmain(){

print(“Hello World! “)

print(“I am learning Kotlin. “)

print(“It is awesome!”)

}

 

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).

// This is a comment

println(“Hello World”)

 

println(“Hello World”)// This is a comment

 

Multi-line Comments

Multi-line comments start with /* and ends with */.

Any text between /* and */ will be ignored by Kotlin.

/* The code below will print the words Hello World

to the screen, and it is amazing */

println(“Hello World”)

 

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 (=):

varvariableName=value

valvariableName=value

 

fun main() {

var name = “John”

valbirthyear = 1975

 

println(name)

println(birthyear)

}

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).

fun main() {

var name = “John” // String

valbirthyear = 1975 // Int

println(name)

println(birthyear)

}

Kotlin Data Types

In Kotlin, the type of a variable is decided by its value:

valmyNum=5// Int

valmyDoubleNum=5.99// Double

valmyLetter=’D’// Char

valmyBoolean=true// Boolean

valmyText=”Hello”// String

 

fun main() {

valmyNum: Int = 5                // Int

valmyDoubleNum: Double = 5.99    // Double

valmyLetter: Char = ‘D’          // Char

valmyBoolean: Boolean = true     // Boolean

valmyText: String = “Hello”      // String

println(myNum)

println(myDoubleNum)

println(myLetter)

println(myBoolean)

println(myText)

}

 

Kotlin Operators

Operators are used to perform operations on variables and values.

Arithmetic Operators

Arithmetic operators are used to perform common mathematical operations.

+  –   *   /    ++   —

fun main() { 

var x = 5

var y = 3

println(x + y) 

}

Kotlin Assignment Operators

Assignment operators are used to assign values to variables.

In the example below, we use the assignment operator (=) to assign the value 10 to a variable called x:

+=   -=   *=    /=

fun main() { 

var x = 10

  x += 5

println(x) 

}

Kotlin Comparison Operators

Comparison operators are used to compare two values, and returns a Boolean value: either true or false.

==   !=    ><>=     <=

fun main() { 

var x = 5

var y = 3

println(x == y) // returns false because 5 is not equal to 3

}

Kotlin Logical Operators

Logical operators are used to determine the logic between variables or values:

And (&&)     or(||)     not(!)

fun main() { 

var x = 5

println(x > 3 && x < 10) // returns true because 5 is greater than 3 AND 5 is less than 10

}

fun main() { 

var x = 5

println(x > 3 || x < 4) // returns true because one of the conditions are true (5 is greater than 3, but 5 is not less than 4)

}

fun main() { 

varmyBool = true

println(!myBool) // returns false because the ! (not) operator reverses the result

}

Kotlin Strings

Strings are used for storing text.

A string contains a collection of characters surrounded by double quotes:

var greeting =”Hello”

 

fun main() {

var greeting: String = “Hello”

println(greeting)

}

Access a String

To access the characters (elements) of a string, you must refer to the index number inside square brackets.

String indexes start with 0. In the example below, we access the first and third element in txt:

fun main() {

var txt = “Hello World”

println(txt[0]) // first element/character

println(txt[2]) // third element/character

}

String Length

A String in Kotlin is an object, which contain properties and functions that can perform certain operations on strings, by writing a dot character (.) after the specific string variable. For example, the length of a string can be found with the length property:

fun main() {

var txt = “ABCDEFGHIJKLMNOPQRSTUVWXYZ”

println(“The length of the txt string is: ” + txt.length);

}

String Functions

There are many string functions available, for example toUpperCase() and toLowerCase():

fun main() {

var txt = “Hello World”

println(txt.toUpperCase())

println(txt.toLowerCase())

}

Comparing Strings

The compareTo(string) function compares two strings and returns 0 if both are equal:

fun main() {

var txt1 = “Hello World”

var txt2 = “Hello World”

println(txt1.compareTo(txt2))  // Outputs 0 (they are equal)

}

Finding a String in a String

The indexOf() function returns the index (the position) of the first occurrence of a specified text in a string (including whitespace):

fun main() {

var txt = “Please locate where ‘locate’ occurs!”

println(txt.indexOf(“locate”))

}

Quotes Inside a String

To use quotes inside a string, use single quotes (‘):

fun main() {

var txt1 = “It’s alright”

var txt2 = “That’s great”

println(txt1)

println(txt2)

}

String Concatenation

The + operator can be used between strings to add them together to make a new string. This is called concatenation:

fun main() {

varfirstName = “John”

varlastName = “Doe”

println(firstName + ” ” + lastName)

}

 

You can also use the plus() function to concatenate two strings:

fun main() {

varfirstName = “John “

varlastName = “Doe”

println(firstName.plus(lastName))

}

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.

Just refer to the variable with the $ symbol:

fun main() {

varfirstName = “John”

varlastName = “Doe”

println(“My name is $firstName $lastName”)

}

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.

fun main() {

valisKotlinFun: Boolean = true

valisFishTasty: Boolean = false

println(isKotlinFun)   // Outputs true

println(isFishTasty)   // Outputs false

}

Boolean Expression

A Boolean expression returns a Boolean value: true or false.

You can use a comparison operator, such as the greater than (>) operator to find out if an expression (or a variable) is true:

fun main() {

val x = 10

val y = 9

println(x > y) // Returns true, because 10 is greater than 9

}

Kotlin Conditions and If..Else

Kotlin supports the usual logical conditions from mathematics:

  • Less than: a < b
  • Less than or equal to: a <= b
  • Greater than: a > b
  • Greater than or equal to: a >= b
  • Equal to a == b
  • Not Equal to: a != b

Kotlin has the following conditionals:

  • Use if to specify a block of code to be executed, if a specified condition is true
  • Use else to specify a block of code to be executed, if the same condition is false
  • Use else if to specify a new condition to test, if the first condition is false
  • Use when to specify many alternative blocks of code to be executed

Kotlin if

Use if to specify a block of code to be executed if a condition is true.

if(condition){

// block of code to be executed if the condition is true

}

fun main() {

if (20 > 18) {

println(“20 is greater than 18”)

  }

}

fun main() {

val x = 20

val y = 18

if (x > y) {

println(“x is greater than y”)

  }

}

Kotlin else

Use else to specify a block of code to be executed if the condition is false.

if(condition){

// block of code to be executed if the condition is true

}else{

// block of code to be executed if the condition is false

}

fun main() {

val time = 20

if (time < 18) {

println(“Good day.”)

  } else {

println(“Good evening.”)

  }

}

Kotlin else if

Use else if to specify a new condition if the first condition is false.

if(condition1){

// block of code to be executed if condition1 is true

}elseif(condition2){

// block of code to be executed if the condition1 is false and condition2 is true

}else{

// block of code to be executed if the condition1 is false and condition2 is false

}

fun main() {

val time = 22

if (time < 10) {

println(“Good morning.”)

  } else if (time < 20) {

println(“Good day.”)

  } else {

println(“Good evening.”)

  }

}

Kotlin when

Instead of writing many if..else expressions, you can use the when expression, which is much easier to read.

It is used to select one of many code blocks to be executed:

fun main() {

val day = 4

 

val result = when (day) {

    1 -> “Monday”

    2 -> “Tuesday”

    3 -> “Wednesday”

    4 -> “Thursday”

    5 -> “Friday”

    6 -> “Saturday”

    7 -> “Sunday”

else -> “Invalid day.”

  }

println(result)

}

This is how it works:

  • The when variable (day) is evaluated once
  • The value of the day variable is compared with the values of each “branch”
  • Each branch starts with a value, followed by an arrow (->) and a result
  • If there is a match, the associated block of code is executed
  • else is used to specify some code to run if there is no match
  • In the example above, the value of day is 4, meaning “Thursday” will be printed

Loops

Loops can execute a block of code as long as a specified condition is reached.

Loops are handy because they save time, reduce errors, and they make code more readable.

Kotlin While Loop

The while loop loops through a block of code as long as a specified condition is true:

while(condition){

// code block to be executed

}

fun main() {

var i = 0

while (i < 5) {

println(i)

i++

  }

}

The Do / While Loop

The do..while loop is a variant of the while loop. This loop will execute the code block once, before checking if the condition is true, then it will repeat the loop as long as the condition is true.

do{

// code block to be executed

}

while(condition);

fun main() {

var i = 0;

do {

println(i)

i++

  }

while (i < 5)

}

Kotlin Break

The break statement is used to jump out of a loop.

This example jumps out of the loop when i is equal to 4:

fun main() {

var i = 0

while (i < 10) {

println(i)

i++

if (i == 4) {

break

    }

  }

}

Kotlin Continue

The continue statement breaks one iteration (in the loop), if a specified condition occurs, and continues with the next iteration in the loop.

This example skips the value of 4:

var i = 0

while (i < 10) {

if (i == 4) {

i++

continue

  }

println(i)

i++

}

Kotlin Arrays

Arrays are used to store multiple values in a single variable, instead of creating separate variables for each value.

To create an array, use the arrayOf() function, and place the values in a comma-separated list inside it:

val cars =arrayOf(“Volvo”,”BMW”,”Ford”,”Mazda”)

Access the Elements of an Array

You can access an array element by referring to the index number, inside square brackets.

In this example, we access the value of the first element in cars:

fun main() {

val cars = arrayOf(“Volvo”, “BMW”, “Ford”, “Mazda”)

println(cars[0])

}

Change an Array Element

To change the value of a specific element, refer to the index number:

cars[0]=”Opel”

fun main() {

val cars = arrayOf(“Volvo”, “BMW”, “Ford”, “Mazda”)

cars[0] = “Opel”

println(cars[0])

}

Array Length / Size

To find out how many elements an array have, use the size property:

fun main() {

val cars = arrayOf(“Volvo”, “BMW”, “Ford”, “Mazda”)

println(cars.size)

}

Check if an Element Exists

You can use the in operator to check if an element exists in an array:

fun main() {

val cars = arrayOf(“Volvo”, “BMW”, “Ford”, “Mazda”)

if (“Volvo” in cars) {

println(“It exists!”)

  } else {

println(“It does not exist.”)

  }

}

Loop Through an Array

Often when you work with arrays, you need to loop through all of the elements.

You can loop through the array elements with the for loop, which you will learn even more about in the next chapter.

The following example outputs all elements in the cars array:

fun main() {

val cars = arrayOf(“Volvo”, “BMW”, “Ford”, “Mazda”)

for (x in cars) {

println(x)

  }

}

KotlinFor Loop

Often when you work with arrays, you need to loop through all of the elements.

To loop through array elements, use the for loop together with the in operator:

fun main() {

val cars = arrayOf(“Volvo”, “BMW”, “Ford”, “Mazda”)

for (x in cars) {

println(x)

  }

}

Kotlin Ranges

With the for loop, you can also create ranges of values with “..”:

fun main() {

for (chars in ‘a’..’x’) {

println(chars)

  }

}

fun main() {

for (nums in 5..15) {

println(nums)

  }

}

Check if a Value Exists

You can also use the in operator to check if a value exists in a range:

fun main() {

valnums = arrayOf(2, 4, 6, 8)

if (2 in nums) {

println(“It exists!”)

  } else {

println(“It does not exist.”)

  }

}

fun main() {

val cars = arrayOf(“Volvo”, “BMW”, “Ford”, “Mazda”)

if (“Volvo” in cars) {

println(“It exists!”)

  } else {

println(“It does not exist.”)

  }

}

Kotlin Functions

function is a block of code which only runs when it is called.

You can pass data, known as parameters, into a function.

Functions are used to perform certain actions, and they are also known as methods.

Predefined Functions

So it turns out you already know what a function is. You have been using it the whole time through this tutorial!

For example, println() is a function. It is used to output/print text to the screen:

fun main() {

println(“Hello World”)

}

Create Your Own Functions

To create your own function, use the fun keyword, and write the name of the function, followed by parantheses ():

funmyFunction(){

println(“I just got executed!”)

}

Call a Function

Now that you have created a function, you can execute it by calling it.

To call a function in Kotlin, write the name of the function followed by two parantheses ().

In the following example, myFunction() will print some text (the action), when it is called:

funmyFunction() {

println(“I just got executed!”)

}

 

fun main() {

myFunction()

}

A function can be called multiple times, if you want:

funmyFunction() {

println(“I just got executed!”)

}

 

fun main() {

myFunction()

myFunction()

myFunction()

}

Kotlin – What is OOP?

OOP stands for Object-Oriented Programming.

Procedural programming is about writing procedures or methods that perform operations on the data, while object-oriented programming is about creating objects that contain both data and methods.

Object-oriented programming has several advantages over procedural programming:

  • OOP is faster and easier to execute
  • OOP provides a clear structure for the programs
  • OOP helps to keep the Kotlin code DRY “Don’t Repeat Yourself”, and makes the code easier to maintain, modify and debug
  • OOP makes it possible to create full reusable applications with less code and shorter development time

Kotlin – What are Classes and Objects?

Classes and objects are the two main aspects of object-oriented programming.

Kotlin Classes/Objects

Everything in Kotlin is associated with classes and objects, along with its properties and functions. For example: in real life, a car is an object. The car has properties, such as brand, weight and color, and functions, such as drive and brake.

Create a Class

To create a class, use the class keyword, and specify the name of the class:

class Car {

var brand =””

var model =””

var year =0

}

Create an Object

Now we can use the class named Car to create objects.

In the example below, we create an object of Car called c1, and then we access the properties of c1 by using the dot syntax (.), just like we did to access array and string properties:

class Car {

var brand = “”

var model = “”

var year = 0

}

 

fun main() {

val c1 = Car()

  c1.brand = “Ford”

  c1.model = “Mustang”

  c1.year = 1969

 

println(c1.brand)

println(c1.model)

println(c1.year)

}

Multiple Objects

You can create multiple objects of one class:

class Car {

var brand = “”

var model = “”

var year = 0

}

 

fun main() {

val c1 = Car()

  c1.brand = “Ford”

  c1.model = “Mustang”

  c1.year = 1969

 

val c2 = Car()

  c2.brand = “BMW”

  c2.model = “X5”

  c2.year = 1999

 

println(c1.brand)

println(c2.brand)

}

Kotlin Constructor

In the previous chapter, we created an object of a class, and specified the properties inside the class, like this:

class Car {

var brand = “”

var model = “”

var year = 0

}

 

fun main() {

val c1 = Car()

  c1.brand = “Ford”

  c1.model = “Mustang”

  c1.year = 1969

 

println(c1.brand)

println(c1.model)

println(c1.year)

}

In Kotlin, there’s a faster way of doing this, by using a constructor.

A constructor is like a special function, and it is defined by using two parantheses () after the class name. You can specify the properties inside of the parantheses (like passing parameters into a regular function).

The constructor will initialize the properties when you create an object of a class. Just remember to specify the type of the property/variable:

class Car(var brand: String, var model: String, var year: Int)

 

fun main() {

val c1 = Car(“Ford”, “Mustang”, 1969)

 

println(c1.brand)

println(c1.model)

println(c1.year)

}

class Car(var brand: String, var model: String, var year: Int)

 

fun main() {

val c1 = Car(“Ford”, “Mustang”, 1969)

val c2 = Car(“BMW”, “X5”, 1999)

val c3 = Car(“Tesla”, “Model S”, 2020)

 

println(c1.brand)

println(c2.brand)

println(c3.brand)

}

Kotlin Class Functions

You can also use functions inside a class, to perfom certain actions:

Example

Create a drive() function inside the Car class and call it:

class Car(var brand: String, var model: String, var year: Int) {

  // Class function

fun drive() {

println(“Wrooom!”)

  }

}

 

fun main() {

val c1 = Car(“Ford”, “Mustang”, 1969)

 

  // Print property values

println(c1.brand + ” ” + c1.model + ” ” + c1.year)

 

  // Call the function

c1.drive()

}

Class Function Parameters

Just like with regular functions, you can pass parameters to a class function:

Example

Create two functions: drive() and speed(), and pass parameters to the speed() function:

class Car(var brand: String, var model: String, var year: Int) {

  // Class function

fun drive() {

println(“Wrooom!”)

  }

 

  // Class function with parameters

fun speed(maxSpeed: Int) {

println(“Max speed is: ” + maxSpeed)

  }

}

 

fun main() {

val c1 = Car(“Ford”, “Mustang”, 1969)

 

  // Print property values

println(c1.brand + ” ” + c1.model + ” ” + c1.year)

 

  // Call the functions

c1.drive()

c1.speed(200)

}

Kotlin Inheritance (Subclass and Superclass)

In Kotlin, it is possible to inherit class properties and functions from one class to another. We group the “inheritance concept” into two categories:

  • subclass (child) – the class that inherits from another class
  • superclass (parent) – the class being inherited from

In the example below, MyChildClass (subclass) inherits the properties from the MyParentClass class (superclass):

// Superclass

open class MyParentClass {

val x = 5

}

 

// Subclass

classMyChildClass: MyParentClass() {

funmyFunction() {

println(x) // x is defined in the superclass

  }

}

 

// Create an object of the MyChildClass and call myFunction

fun main() {

valmyObj = MyChildClass()

myObj.myFunction()

}