Kotlin Tutorial for Beginners (Examples)

What is Kotlin?

Kotlin is an open-source statically typed programming language that runs on Java Virtual Machine (JVM). It combines Object Oriented Programming (OOPs) and functional programming in unrestricted, self-sufficient, and distinctive platforms. It also allows the twinning of functionalities by miniature codes. Kotlin is a general-purpose programming language which was designed by JetBrains.

History of Kotlin

Here, are important landmarks from the history of Kotlin:

Year Event
2016 Kotlin v1.0 was launched
2017 Announcement of Google on the first-class support of kotlin in android
2018 Kotlin v1.2 comes with add on distributing codes between JVM and JavaScript
2019 Google announced Kotlin as its preferred programming language for Android Application Developers
2021 On September 20, 2021, Kotlin v1.5.31 was launched.

Reasons of of using Kotlin

Here, are some important reasons why Kotlin is used widely:

  • Kotlin is a statically-typed language which is very easy to read and write.
  • Kotlin programs do not require semicolons in their program. This makes the code easy and more readable.
  • This languare allows exchange and use of information from Java in various ways. Moreover, Java and Kotlin code can co-exist in the same project.
  • Kotlin’s type system is aimed to eliminate NullPointerException from the code.
  • It’ll take you less time to write new code in Kotlin. It’s even easier to deploy kotlin code and to maintain it at scale.

Features of Kotlin

Here are a few features of the Kotlin that will make you sure of the progress path of the programming language.

Trimmed Coding:

Kotlin is an OOPs-based programming language where code line can be trimmed up to 40 % that which makes Kotlin an ideal choice for software or web development.

Open-Source:

Kotlin for Android utilizes JVM and combines the features of OOPs and functional-oriented programming.

Fast Compilation:

it is easy to compile the code when working with Kotlin that results in better performance for android development, and it will also explain which type of data function can be used in the entire code.

Extension Functions:

Kotlin can support a variety of extension functions without making any changes to the code. it helps in making existing code more appealing and magnificent for developers.

For Example:

Fun String.removeFirstLastChar():
String = this.substring(1, this.length -1)

This code will assist in trimming down the first and the last character of the string, we can apply it as:

Val string1 = "Today is cloudy."
Val string2 = string1.removeFirstLastChar()

Null Safety:

In Kotlin, the system distinguishes between null references and not null references as shown in below Kotlin example.

For example, a String variable cannot hold null:

Var string1: String = "Today is Sunday"
String1 = null  // compilation error
To permit null, we can adjoin the nullable variable :
Var string2: String? = "Today is Sunday"
String2 = null
print(string2)

Interoperable:

Kotlin code can be used by Java, and Java codes can be used with Kotlin. So, if you have knowledge about OOPs programming, it is easy to switch to Kotlin’s development. Also, if there are some applications written in Java, then they can be used with Kotlin’s environment.

Robust Tools:

Like Java, Kotlin code can also be written using IDE or using the command-line interface. It is easy to work with IDE, and syntax errors are also reduced dramatically. At the same time, when you are working with a command-line interface, code has to be compiled first.

Smart Cast:

Smart casting basically helps to cut down the application costs and improves its speed or performance. It works on managing the efficiency of code using type casting or immutable values.

For example, if the string is identified, then it’s length and count and can be found with the help of Smart Cast function:

Val string1: Any = "Today is Monday"
when(string1)
{
is String  -> string1.length
Is Int -> string1.inc()
}

Low Cost of Adoption:

Kotlin is preferred by enterprises because of its lost cost of adoption. Most importantly, it is easy to learn by developers, especially having a programming background.

Kotlin Environment Setup

Following are the steps which help you in setting up a working environment by installing Kotlin.

Step 1) Install Java

As we have discussed earlier that Kotlin is based on Java, so you have to install Java first when planning to adopt Kotlin. Refer our Java Installation Tutorial.

Step 2) Install Java IDEs

Luckily, there are multiple Java IDEs to choose from. Here we have given download links to make things a little easier for you.

In this Kotlin tutorial, we will use Eclipse.

Step 3) Install Kotlin

For Installing Kotlin in Eclipse, go to the Help section in Eclipse and click the Eclipse Marketplace option.

Kotlin Environment Setup

Now, Type the Kotlin keyword into the search box. Click on Go option to list the plugin. It will give you a link of Kotlin plug-in, you need to install the plug-in from the given link.

Kotlin Environment Setup

Please restart the Eclipse IDE, once the installation is complete. You can find a shortcut icon in the top right corner of Eclipse IDE. It is a quick access method.

Kotlin Environment Setup

Another way of accessing Kotlin in Eclipse IDE is, go to the Windows, Perspectives, Open Perspectives, then choose Others option. Here, you can check a list of plugins installed later, as given below.

Kotlin Environment Setup

Once, you have verified the Kotlin installation, let us create the first Kotlin program in the next step.

Step 4) First Kotlin Program

Start with your first Kotlin project. From the File menu, choose the New option, then select others and start with a new Kotlin project from the list.

Kotlin Environment Setup

Now, you have to define a name for the project, and you are ready to work with Kotlin.

Kotlin Environment Setup

With these simple steps, it is easy downloading Eclipse and Kotlin on your system and write your first Kotlin program right away.

Architecture of Kotlin

A well-built architecture is important for an application to scale up its features and meet the expectations of the end-user base. Kotlin has its own peculiar and distinctive architecture to allocate the memory and to get quality outcomes for the developers and end-users.

Kotlin’s coroutines and classes architect the core in such a way to produce less boilerplate code, amplify the performance, and reinforce the efficiency. There are a variety of scenarios where the kotlin compiler can react differently, especially whenever it is earmarking various kinds of languages.

Architecture of Kotlin
Architecture of Kotlin

In the architecture diagram, it is clear that code execution is done in three easy steps.

  1. In the first step, “.kt” or kotlin file is added to the compiler.
  2. In the second step, Kotlin compiler converts the code into bytecode.
  3. In the third step, bytecode is put into Java Virtual Machine and executed by the JVM.

When a couple of byte coded file operates on JVM, they kindle the mutual communication among themselves, which is why the feature in Kotlin called interoperability for java ook birth

The transpiring of Kotlin to JavaScript happens when Kotlin targets JavaScript.

When the JavaScript’s target is chosen, any code of Kotlin that is a part of the library that sails with Kotlin is than spilled with JavaScript. However, the Java Development Kit(JDK) or any java library used is excluded.

A non-Kotlin file is not taken into consideration during such operation. While targeting JavaScript .kt file is converted into ES5.1 by Kotlin compiler to generate a consistent code for JavaScript. Kotlin compiler endeavors an optimal size output, interoperability with existing module, same functionality with the standard library, and output that is JavaScript readable.

It is clear from the discussion that Kotlin Compilers can create a more efficient, competent, and independent code that further results in a high-performing software product.

Kotlin Variable

Variables are used to store data to be manipulated and referenced in the program. It is fundamentally a unit of storing data and labeling it waits for an expository alias so that the program is simple to read and easy to understand. In other words, we can say that variables are the containers to collect information.

In Kotlin, all the variables should be declared. However, if any variable is not declared, then it pops out to be a syntax error. Also, the declaration of the variable determines the type of data we are allowing to store in the variable. In Kotlin, variables can be defined using val and var keywords. Here is the syntax of declaring variables in Kotlin:

Var day = "Monday"
Var number = 3

Here, we have declared the local variable day whose value is “Monday’ and whose type is String and another local variable number whose value is 3 and whose type is Int because here the literal is of the type integer that is 3.

Local variables are customarily declared and initialized simultaneously. We can also perform certain operations while initializing the Kotlin variable.

We can perform an operation on the variable of the same data type, as in here num1 and num2 both are of the same data type that is Int, whereas day is of the string data type. Ergo, it will show an error. Here is one another technique how can you define variables in Kotlin.

var day : String = "GURU99"
var num : Int = 100

Let see how var and val keywords are different from each other.

Var :

Var is like a generic variable used in any programming language that can be utilized multiple times in a single program. Moreover, you can change its value anytime in a program. Therefore, it is known as the mutable variable.

Here is an example of mutable variable in Kotlin:

var num1 = 10
Var num2 = 20
Num1 = 20
print(num1 + num2) // output : 40

Here the value of num1 that is 20, is overwritten by the previous value of num1 that is 10. Therefore the output of num1 + num2 is 40 instead of 30.

Val :

Val is like a constant variable, and you cannot change its value later in the program, which neither can be assigned multiple times in a single program and can be used only once in a particular program. Ergo, it is known as an immutable variable.

Here is an Kotlin program example of immutable variables in Kotlin:

Val num1 = 10
Var num2 = 20

Here, the value of num1 that is 10 cannot be overwritten by the new value of num1 that is 20, as it is of val type that is constant. Therefore, the output is 30 instead of 40.

Note: In Kotlin, immutable variables are preferred over mutable variables.

Data Types in Kotlin

Data types are set of relatable values and describe the operations that can be operated on them. Similar to other programming languages, Kotlin also has its predefined set of data types like Int, Boolean, Char, Double, etc.

In Kotlin, every data type is considered as an object.

Now in this Kotlin basic Tutorial, let’s dive deeper into the predefined data types used in Kotlin.

Numbers :

Kotlin serves a set of built-in data types known as numbers, which are sub-categorize as Integers and Floating-Point Numbers.

Integers :

Integers are the category of numbers that has four types:

Type Size (bits) Min value Max value
Byte 8 -128 127
Short 16 -32768 32767
Int 32 -2,147,483,648 (-231) 2,147,483,647 (231 – 1)
Long 64 -9,223,372,036,854,775,808 (-263) 9,223,372,036,854,775,807 (263 – 1)

Floating Point Numbers :

Floating Point Numbers are the non-Integer numbers that carry some decimal values.

Float: Float is a 32- bit single-precision floating-point value.

Example: var: Float x = 3.25600

Double: Double is a 64- bit double – precision floating point value.

Example: var: Double y = 2456.345587

Booleans :

Booleans data type in Kotlin is significant to represent the logical values. There are only two possible values in Boolean that is either true or false.

For Example: val day = true

Val day2 = false

Character :

Characters in Kotlin are represented with the help of the keyword called char. In Kotlin, single quotes represent the declaration of char. In java, char are sometimes used as numbers that is not possible in kotlin.

For Example:

val onechar = 'x'
print(onechar) //  output : x
Val onedigit = '7'
print(onedigit) // output : 7

Kotlin Type Conversion or Kotlin Type Casting

Type Conversion is a procedure of converting one type of data variable into another data type variable. It is enormously, also known as Type Casting.

Eminently, in Java, implicit type of type conversion or implicit type of typecasting of a smaller data type to larger data type is supported.

For Example : int abc = 15;
Long bcd = abc; // compiles successfully

However, in kotlin, implicit conversion of a smaller data type to a larger data type is not at all supported that is int data type cannot be converted into long data type implicitly.

For Example : var abc = 15
Val bcd : Long = abc // error

However, In Kotlin, type conversion is done explicitly. Here comes the guidance of helper functions that guides the conversion of one data type variable to another.

There are certain helper function which are pre – owned for the conversion of one data type to another :

toInt()

toByte()

toShort()

toChar()

toLong()

toFloat()

toDouble()

For Example : var abc = 15
Val bcd : Long = abc.toLong() // compiles successfully

Kotlin Operators

Operators are momentous and special characters or symbols that assures the operations in operands that have variables and values. In Kotlin, there is a set of operators that are used in different operations like arithmetic operations, assignment operations, comparison operations, etc.

Arithmetic Operators :

Arithmetic operators are used for addition, subtraction, multiplication, division, and modulus.

Operator Meaning
+ Addition (also used for string concatenation)
Subtraction Operator
* Multiplication Operator
/ Division Operator
% Modulus Operator

For Example:

var x = 10
var y = 20
var z = ( ( x + y ) * ( x + y ) ) / 2     

Here the output of the following code is 45.

Comparison Operators :

Comparison operator is used to compare two values, two variables or two numbers. It is used with the greater than symbol( > ), less than symbol( < ) and equal to symbol( ==), not equal to symbol( != ), greater than equal to symbol( >= ), less than equal to symbol(<= ). It always results in true or false.

For Example:

var x = 10
Var y =20
Var z = x < y // Output : true
Var w = x > y // Output : false
Var m = x == y // Output : false

Assignment Operators :

Assignment Operators are used to assign the arithmetic operated values. It is used with the symbols like +=, -=, *=, /=, %=.

For Example:

var x = 10
var y = 20
var x + = y // Output : 30
Var y - = x // Output : 10
Var x * = y // Output : 200

Increment and Decrement Operators :

Increment and decrement operators are used to increment and decrement the values of the variable or number. It is used with the help of symbols like ++ and —.

There are two types of increment and decrement that are pre-increment ++a, post-increment a++, pre decrement –b, post decrement b–.

For Example:

var a = 10
var b = 20
var c = a++ // Output: 11
var d = b— //Output : 19     

Kotlin Arrays

An Array is the homogenous set of data types and is one of the most fundamental data types which is used to store the same types of data in the contiguous memory location. An Array is significant for the organization of data in any programming language so that multiple data stored ant a single place is easy to search or sort.

In Kotlin, arrays are a mutable collaboration of the same data types rather than being native data types.

Here are certain properties of an array in Kotlin

  • The size of the array cannot be changed once declared.
  • Arrays in Kotlin are mutable.
  • Arrays are stored in contiguous memory locations.
  • An array can be accessed with the help of indexes like a[1], a[2], et – cetera.
  • The index of an array starts with zero that is a[0].

In Kotlin, an array can be defined in two different methods

By Using arrayOf() Function :

In Kotlin, there is a major usage of library functions. One such library function is arrayOf() function, which is used to define an array by passing the values of the variables to the function.

For Example: Implicit type declaration of array using arrayOf() function

val x = arrayOf(1,2,3,4,5,6,7,8,9)

For Example: Explicitly type declaration of array using arrayOf() function.

Val y = arrayOf<Int>(1,2,3,4,5,6,7,8,9)

By Using Array Constructor :

In Kotlin, there is a class with the name of Array. Therefore, it is feasible to use an array of the constructor to create an array. The array in constructor holds two major parameters.

What is the Index of an Array in Kotlin?

The function where an array index is acceptable to return the initial value of the index.

For Example:

val abc = Array(7 , { i -> i*1})

Here, the value of array is 7 and lambda expression is used to initialize the values of the element.

There are also various methods to access and modify the arrays using certain functions. Therefore, there are two member functions get() and set(), which are used to access class array’s objects.

For Example:

val x = arrayOf(10,20,30,40,50,60,70,80,90)
val y = x.get(0) // Output 10

Here, the output is 10 since the value at the index 0 of array is 10

Note : get() takes only single values

For Example:

val x = arrayOf(10,20,30,40,50,60,70.80.90)
val y = x.set(2, 3) //

Output : 30 40

Here, the output is 30 and 40 since the value at the index 2 of array is 30 and at index 3 it is 40.

Note: set() takes multiple values of an array.

Kotlin Strings

A string is a basic data type in any programming language. A string is nothing but a sequence of characters. The String class represents character strings. In Kotlin, all strings are objects of the String class, which means string literals are implemented as instances of the class.

Syntax:

 Val myString = "Hey there!"

Kotlin Collection

A collection contains several objects of a similar type, and these objects in the collection are called elements or items. Collection can help to store, retrieve, manipulate, and aggregate data.

Types of Collections:

Immutable collection

This type of collection support read-only functionalities. One cannot modify its elements.

Methods include:

  • List – listOf() and listOf<T>()
  • Set – setOf()
  • Map – mapOf()

Mutable Collection

It supports both read and write functionality.

Methods include

  • List – mutableListOf(),arrayListOf() and ArrayList
  • Set – mutableSetOf(), hashSetOf()
  • Map – mutableMapOf(), hashMapOf() and HashMap

Kotlin Functions

Functions in any programming language is a group of similar statements which is designated to perform a specific task. Functions allow a program to break it into various small code blocks. This division of code increases the readability of code, reusability of code, and makes a program easy to manage.

As Kotlin is known as a statically typed language. Here, the ‘fun’ keyword is used to declare a function. In Kotlin, there are two types of functions which solely depends upon its availability in the standard library or user definition. They are:

  • Standard library function
  • User-defined function

Kotlin Function

Kotlin Functions

Now, let us discuss them in detail with Kotlin code examples.

Standard Library Function

They are built-in library functions that can be defined implicitly and available for use.

For Example 2:

fun main(args: Array<String>){  
var number = 9  
var result = Math.sqrt(number.toDouble())  
print("$result")  
}  

Output:

3.0

sqrt() is a function defined in the library which returns the square root of a number.

print() function prints message to a standard output stream.

User-defined Function

As the name suggests, these functions are usually created by users, and they can be used for advanced programming.

Here, functions are declared using the ‘fun’ keyword.

For Example 3:

fun functionName(){
//body of the code
}

Here, we call the function to run codes inside the body functionName()

Kotlin function examples:

fun main(args: Array<String>){  
    sum()  
    print("code after sum")  
}  
fun sum(){  
    var num1 =8  
    var num2 = 9  
    println("sum = "+(num1+num2))  
}  

Output:

sum = 17

code after sum

Exception Handling in Kotlin

Exception in programming is defined as a runtime problem which occurs in the program, leading it to terminate. This issue can occur due to less memory space, array out of bond, conditions like division by zero. To curb these types of issues in code execution, exception handling is used.

Exception handling is defined as the technique which handles the runtime problems and also maintains the program flow during execution.

Kotlin uses the ‘throw’ expression to throw an exception object. Here all exception classes are descendants of class Throwable.

Throw MyException(“throws exception”)

There are four types of exceptions in exception handling. They are:

  • try – This block contains statements which might create the exception. It is always followed by either catch or finally or both.
  • catch – it catches an exception thrown from the try block.
  • finally – It always checks whether the exception is handled or not.
  • throw – It is used to throw an exception explicitly.

Try catch:

In try-catch block in exception handling, try block encloses the code, which may throw an exception and catch block catches the expression and handles it.

Syntax of try catch block:

try{    
//code with exception    
}catch(e: SomeException){  
//code handling exception  
}    

Syntax of try with finally block

try{    
//code with exception    
}finally{  
// code finally block  
}   

Finally:

In Kolin, finally block always checks whether the exception is handled or not, making it a very important statement of exception handling.

For Example 4:

In this code snippet, the exception occurs, and it is handled.

fun main (args: Array<String>){  
    try {  	
        val data =  9/ 0  
        println(data)  
    } catch (e: ArithmeticException) {  
        println(e)  
    } finally {  
        println("finally block executes")  
    }  
    println("write next code")  
}  

Output:

java.lang.ArithmeticException: / by zero
finally block executes
write next code

Throw:

Throw block throws an explicit exception. Moreover, it is used to throw custom exceptions.

Syntax:

Throw SomeException()

Throw SomeException()

Example:

fun main(args: Array<String>) {
    try{
        println("Exception is not thrown yet")
        throw Exception("Everything is not well")
        println("Exception is thrown")
    }
    catch(e: Exception){
        println(e)

    }
    finally{
        println("You can't ignore me")
    }
}

Output:

Kotlin Example

Kotlin Null Safety

The types of systems that support Kotlin majorly distinguishes among the references that can carry nullable references, and the ones cannot carry nullable references. Kotlin is a null safety language aimed to eliminate the null pointer exception or null reference from the code, which is deliberately known as A Billion Dollar Mistake.

The most conventional stumbling block of many programming languages is that while accessing a member of a null reference, it results to be a NullPointerException, which could be because of !! operator or this constructor used somewhere else and passed at another point of code. The nullable property requires confirmation for the null check every time prior to its utilization.

In Kotlin, the system distinguishes between null references and not null references.

For example, a String variable cannot hold null:

For Example 5:

fun main(args: Array<String>){
    var x: String = "GURU99 is the only place where you will get maximum technical content!" // Not Null by default
    println("x is : $x")
    // You cannot assign null variable to not-nullable variables 
    // a=null // it will give compilation error
    var y: String? = "Thanks for visiting GURU99" 
// Nullable Variable
    println("y is : $y")
    y = null
    println("y is : $y")
}

Output:

Kotlin Null Safety

Kotlin OOPs

The object-oriented programming approach allows a complex code snippet to divide into smaller code blocks by creating objects. These objects mutually share two characteristics: state and behavior.

Here are some of the OOPs elements that we are going to discuss with Kotlin code examples:

  • Class and Objects
  • Constructors
  • Inheritance
  • Abstract Class

Kotlin OOPs

Class in Kotlin

The first before creating an object, we need to define a class that is also known as the blueprint for the object.

Syntax:

class ClassName {
    // property
    // member function
    ... .. ...
}

Objects in Kotlin

While defining a class, we only define the specifications for the object, no other parameter like memory or storage is allocated.

Syntax:

var obj1 = ClassName()

Constructors in Kotlin

A constructor is a way to initialize class properties. It’s a member function called when an object is instantiated. But in Kotlin, it works differently.

There are two types of constructors in Kotlin:

Constructors in Kotlin

Constructors in Kotlin

Primary constructor: Optimized way to initialize a class

Syntax:

class myClass(valname: String,varid: Int) {  
    // class body  
}  

Secondary constructor: Helps to add initialization logic

Kotlin Inheritance

Inheritance occurs when some properties of the parent class are acquired by the child class. Inheritance is allowed when two or more classes have the same properties.

Syntax:

open class ParentClass(primary_construct){
    // common code
  }class ChildClass(primary_construct): ParentClass(primary_construct_initializ){
    // ChildClass specific behaviours
  }

Abstract Class in Kotlin

An abstract class is a class that cannot be instantiated, but we can inherit subclasses from them. ‘abstract ‘ keyword is used to declare an abstract class.

For Example 6:

  open class humanbeings { 
    open fun Eat() { 
        println("All Human being Eat") 
    } 
} 
abstract class Animal : humanbeings() { 
    override abstract fun Eat() 
} 
class Cat: Animal(){ 
    override fun Eat() { 
        println("Cats also loves eating") 
    } 
} 
fun main(args: Array<String>){ 
    val lt = humanbeings() 
    lt.Eat() 
    val d = Cat() 
    d.Eat() 
} 

Output:

Abstract Class in Kotlin

The Present & Future of Kotlin

The Present:

  • Many companies like Netflix, Pinterest, and Corda are using Kotlin to create powerful Android apps.
  • In a short duration of one year, 2016 to 2017, Kotlin became highly popular with amazing programming features.
  • In 2017, Google announced Kotlin as an official programming language for android development.
  • You can quickly replace Java code with Kotlin as it is 100% interoperable with Java and Android.

The Future:

  • Cross-platform game development
  • Cross-platform mobile app development
  • Service-side scripting and microservices
  • Machine learning & data analysis

Summary

  • Kotlin is a programming language proposed by JetBrains in 2010 for multi-platform apps under the Apache 2.0 license.
  • The name Kotlin is derived after the name of Kotlin Island in a similar correspondence of Java after the name of an island called java.
  • In, 2016 Kotlin first version v1.0 was launched
  • Kotlin programs do not require semicolons in their program. This makes the code easy and more readable.
  • Kotlin for Android developers is an OOPs-based programming language where code line can be trimmed up to 40 % that which makes Kotlin an ideal choice for software or web development.
  • In Kotlin, all the variables should be declared using var and val keywords.
  • Similar to other programming languages, Kotlin also has its predefined set of data types like Int, Boolean, Char, Double, etc.
  • In Kotlin, there is a set of operators that are used in different operations like arithmetic operations, assignment operations, comparison operations, etc.
  • In Kotlin, arrays are a mutable collaboration of the same data types rather than being native data types.
  • In Kotlin, arrays are defined using two methods – ArrayOF () and Constructors.
  • Kotlin is a null safety language that helps to remove the null pointer exception or null reference from the code, which is deliberately called A Billion Dollar Mistake.