Author

Animesh

Browsing

Amazing! It’s really nice that you have learned the basics of Kotlin and are comfortable with them. Now, its time to explore deeper topics and help you build strong knowledge of concepts that are actually used in Software Industry frequently. Welcome to Collections!

According to kotlinlang.org, a collection usually contains a number of objects (this number may also be zero) of the same type. Objects in a collection are called elements or items. For example, all the employees in a department form a collection that can be used to calculate their average age.

So, there are basically 3 types of collections in Kotlin as follows:

 

  • List, which is an ordered collection with access to elements by indices – integer numbers that reflect their position. In a list, elements can occur more than once.
  • Set, which is a collection of unique elements. It reflects the mathematical abstraction of the set: a group of objects without repetitions. The set of elements has no significance.
  • Map (or dictionary), which is a set of key-value pairs. Keys are unique, while each of them, maps to exactly one value. Although, the values can be duplicates. Maps are useful for storing logical connections between objects, for example, an employee’s ID and their position.

 

Kotlin – Arrays

In Kotlin, Array has mutable nature with a fixed size. we can perform both read and write operations on Array elements.

Array syntax:

var firstArray = Array<Int>(4){0}

Array declaration:

var firstArray1 = arrayOf(1,2,3,4,5)  
var firstArray2 = arrayOf<Int>(1,2,3,4,5)  
val secondArray = arrayOf<String>("Suresh","Mahesh","Rambabu","Jaiswal","Mihir")  
var thirdArray  = arrayOf(1,2,3, "Ram","Lal")  

Simple example:

 fun main(args: Array<String>){  
    val name = arrayOf<String>("Suresh","Mahesh","Rambabu","Jaiswal","Mihir")  
    var myArray2 = arrayOf<Int>(1,2,3,4,5)  
    var myArray3 = arrayOf(1,2,3,4,5)  
    var myArray4= arrayOf(1,2,3, "Ram","Lal")  
    var myArray5: IntArray = intArrayOf(5,10,15,20,25)  
  
    for(element in name){  
        println(element)  
    }  
  
    println()  
    for(element in myArray2){  
        println(element)  
    }  
    println()  
    for(element in myArray3){  
        println(element)  
    }  
    println()  
    for(element in myArray4){  
        println(element)  
    }  
    println()  
    for(element in myArray5){  
        println(element)  
    }  
  }

//Output:
Suresh
Mahesh
Rambabu
Jaiswal
Mihir

1
2
3
4
5

1
2
3
4
5

1
2
3
Ram
Lal

5
10
15
20
25

Kotlin – Collections

Generally, by using Collection, we can store, retrieve manipulate, and aggregate data.

Collections in Kotlin are broadly categorized into two different forms. These are:

  1. Immutable Collection (or Collection)
  2. Mutable Collection

Now let’s look into Immutable Collection.m

Immutable Collection

Simply known as Collection. They support read-only functionalities. Let’s look at the methods of Immutable collections :

List: listOf(), listOf<T>()

Map: mapOf()

Set: setOf()

Mutable Collection

They support both read and write functionalities. Let’s look at the methods of Immutable collections :

List: ArrayList<T>(), arrayListOf(), mutableListOf()

Map: hashMapOf(), mutableMapOf()

Set: hashSetOf(), mutableSetOf()

Kotlin – List

Its an interface and generic collection of elements. The List interface inherits from Collection<T> class. It is immutable and its methods support only read functionalities.

The elements of List follow the sequence of the insertion order and contain index number same as an array.

List Interface Declaration

public interface List<out E> : Collection<E> (source)

functions

Simple example:

fun main(args: Array<String>){  
    var list = listOf("Ram","Shyam","Mahendra")//This is read only and fixed-size  
    for(element in list){  
        println(element)  
    }  

//Output:
Ram
Shyam
Mahendra

Another simple example:

fun main(args: Array<String>){  
    var stringList: List<String> = listOf<String>("Amar","Akbar","Anthony","Rahul","Ritu")  
    var list: List<String> = listOf<String>("Amar","Akbar","Anthony")  
    for(element in stringList){  
        print(element+" ")  
    }  
    println()  
    println(stringList.get(0))  
    println(stringList.indexOf("Rahul"))  
    println(stringList.lastIndexOf("Rahul"))  
    println(stringList.size)  
    println(stringList.contains("Anthony"))  
    println(stringList.containsAll(list))  
    println(stringList.subList(2,4))  
    println(stringList.isEmpty())  
    println(stringList.drop(1))  
    println(stringList.dropLast(2))  
}  

//Output:
Amar Akbar Anthony Rahul Ritu 
Amar
3
3
5
true
true
[Anthony, Rahul]
false
[Akbar, Anthony, Rahul, Ritu]
[Amar, Akbar, Anthony]

Kotlin – MutableList(mutableListOf())

It can be called as an interface and generic collection of elements, which is mutable in nature. It inherits from Collection<T> class. The methods of this interface support both read and write functionalities. After declaration of elements in MutableList, more elements can be added/removed from it (no fixed size length).

For using MutableList interface, functions can be used –  mutableListOf() or mutableListOf<E>().

The elements of MutableList follow a sequence of the insertion order and contains index number same as array.

MutableList Interface Declaration

interface MutableList<E> : List<E>, MutableCollection<E> (source)

Simple example:

fun main(args: Array<String>){  
    var mutableList = mutableListOf("Suresh","Mahesh","Rajesh","Brijesh")  
  
    for(element in mutableList){  
        println(element)  
    }  
    println()  
    for(index in 0..mutableList.size-1){  
        println(mutableList[index])  
    }  
}  

//Output:
Suresh
Mahesh
Rajesh
Brijesh

Suresh
Mahesh
Rajesh
Brijesh

Another example:

fun main(args: Array<String>){  
    var mutableList1 = mutableListOf("Ram","Suresh")  
    mutableList1.add("Paramjeet")  
    mutableList1.add("Ramnaresh")  
  
    var mutableList2 = mutableListOf<String>()  
    mutableList2.add("Rajiv")  
    mutableList2.add("Ramlal")  
    mutableList2.add("Singham")  
  
    for(element in mutableList1){  
        println(element)  
    }  
    println()  
    for(element in mutableList2){  
        println(element)  
    }  
}  

//Output:
Ram
Suresh
Paramjeet
Ramnaresh

Rajiv
Ramlal
Singham

Kotlin ArrayList class

This class is used to create a dynamic array, meaning its size can be increased or decreased according to requirement. This class provides both read and write functionalities.

While following the sequence of insertion order. ArrayList class is non synchronized and it may contains duplicate elements. The elements of ArrayList class are accessed randomly as it works on index basis.

Constructor of Kotlin ArrayList

Functions of Kotlin ArrayList

Simple example:

fun main(args: Array<String>){  
  
    val arrayList = ArrayList<String>()//Creating an empty arraylist  
    arrayList.add("Samuel")//Adding object in arraylist  
    arrayList.add("Diablo")  
    arrayList.add("John")  
    arrayList.add("Rakesh")  
    arrayList.add("Jinpin")  
    println(".......printing ArrayList.......")  
    for (i in arrayList) {  
        println(i)  
    }  
}  

//Output:
.......printing ArrayList.......
Samuel
Diablo
John
Rakesh
Jinpin

Kotlin ArrayList: arrayListOf

arrayListOf() is one of function of ArrayList class. ArrayList is mutable, providing both read and write functionalities. This function returns an ArrayList type.

Syntax of arrayListOf() function:

inline fun <T> arrayListOf(): ArrayList<T> (source)  
fun <T> arrayListOf(vararg elements: T): ArrayList<T> (source) 

Syntax of arrayListOf() function:

Congrats! on reaching the third post for learning Kotlin. Now lets look at two important topics Exception handling and Null Safety. So, lets start…

Kotlin – Exception Handling

In general terms, exception handling in programming is a technique that allows us to handle the runtime errors caused by exceptions. An exception is an unwanted event that interrupts program’s normal flow. Program execution gets terminated when an exception occurs.

In Kotlin, all exception classes are descendants of class Throwable. To throw an exception object, Kotlin uses throw expression:

throw FirstException("throws an exception")  

Four keywords used in exception handling are:

  • try : try block contains set of statements which might generate an exception. It should be followed by either catch or finally or both.
  • catch : catch block is used to catch the exception that is thrown from try block.
  • finally : finally block is mandatory executed whether exception is handled or not. So it is used to execute important code.
  • throw : throw keyword is used to throw an exception explicitly.

There are two kinds of exceptions in Java (Kotlin’s elder sister 🙂 ) : 

  • Checked exceptions
  • Unchecked exceptions

Thankfully! Kotlin doesn’t support Checked exceptions.

Unchecked exceptions in Kotlin

These are those exceptions that are thrown because of mistakes in your code. They are a direct or indirect subclass of the RuntimeException superclass. 

Examples of unchecked exceptions are following:

  • ArithmeticException: thrown when you divide by zero.
  • ArrayIndexOutOfBoundsException: thrown when an array has been accessed with an illegal index. 
  • SecurityException: thrown by the security manager to indicate a security violation.
  • NullPointerException: thrown when invoking a method or property on a null object.

Suppose if there is a method that might throw an unchecked exception, then the method might not contain any information about the exception thrown on its method declaration. 

try – catch

As the rule goes in Java programming, try – catch are like brother and sister. A try block encloses the code (which may throw an exception) and the catch block is used to handle the exception. This block must be written within the method only. Here, try block must be followed by either catch block or finally block or both.

Simple example:

fun main(args: Array<String>) {
    val a = 5
    val b = 0
    var c : Int
    try {
        c = a/b
    } catch (e : Exception){
        println("Handled exception")
    }
}

//Output:
Handled exception

multi – catch block

In Kotlin, multiple catch blocks are used when different exceptions in try block are generated because we are using different types of operation in try block.

Simple example:

fun main(args: Array<String>) {
    try{
        var num = 5/0
        println(num)
    }
    catch(e: NumberFormatException){
        println("Numberformat exception")
    }
    catch(e: ArrayIndexOutOfBoundsException){
        println("ArrayIndexOutOfBounds")
    }
    catch(e: Exception){
        println("Some Exception occurred")
    }

    println("Out of try-catch block")
}

//Output:
Some Exception occurred
Out of try-catch block

nested try-catch block

A nested try-catch block is used where one try-catch block is implemented into another try block.

Its requirement arises where a block of code generates an exception and within that block another code statements also generates another exception.

Simple example:

fun main(args: Array<String>) {
    try {
        val num = 200 / 2
        println(num)
        try {
            val num2 = 100 / 0
            println(num2)
        }
        catch(e: NumberFormatException){
            println("NumberFormat Exception")
        }
    }
    catch(e: ArithmeticException){
        println("ArithmeticException")
    }
}

//Output:
100
ArithmeticException

finally block

finally block is used to execute compulsory code statement  as such block which is executed always whether an exception is handled or not. 

Simple example:

fun main (args: Array<String>){  
    try {  
        val data = 100 / 2  
        println(data)  
    } catch (e: NullPointerException) {  
        println(e)  
    } finally {  
        println("finally block executes")  
    }  
    println("below code")  
}  

//Output:
50
finally block executes
below code

Also, its interesting to note that finally block is not executed if program exits.

throw keyword

This is used to throw an explicit or custom exception.

Simple example:

fun main(args: Array<String>) {
    print("Please enter your name: ")
    val name = readLine()
    try{
        if (name == "Animesh"){
            throw Exception("You don't have access")
        }
        else
        {
            println("Welcome! You have access")
        }
    }
    catch (e: Exception){
        println(e.message)
    }
}

//Output:
Please enter your name: Animesh
You don't have access

Kotlin – Null Safety

Okay! now, time has come to discuss about Null safety in Kotlin. It is a method to reduce and rather eliminate the risk of null reference from the code statements. Kotlin compiler throws NullPointerException immediately if any null argument is passed without executing any other statements.

Kotlin’s type system eliminates NullPointerException from the code. NullPointerException can only possible on following causes:

  • A forcefull call to throw NullPointerException();
  • Uninitialized this-operator which is available in a constructor passed and used somewhere.
  • Use of external Java code as Kotlin is Java interoperability.

nullable and non-nullable types

Kotlin differentiates between references which can hold null (nullable reference) and which cannot hold null. Generally, types of String are non-nullable. To make string which holds null value, we have to explicitly define them by putting a ? behind the String as: String?

Simple example:

nullable types

fun main(args: Array<String>){  
var str1: String? = "Hi! Android" // nullable variable 
str1 = null  
    print(str1)  
}  

//Output:
null

non-nullable types

val str: String = null // compile time error  
str = "hello" // compile time error Val cannot be reassign  
var str2: String = "Hi! Android "  
str2 = null // compile time error  

Compiler will give error if we assign a null value to a non-nullable string.

checking for null

fun main(args: Array<String>){  
var str: String? = "Hi! Android"     // nullable variable
var len = if(str!=null) str.length else -1  
println("str is : $str")  
println("length of str is : $len")  
  
str = null  
println("string is : $str")  
len = if(str!=null) str.length else -1  
println("length of b is : $len")  
} 

//Output:

str is : Hi! Android
length of str is : 11
string is : null
length of b is : -1

Smart cast

To use nullable types, optionally, we can use smart casts. Smart cast is a feature in which Kotlin compiler tracks conditions inside if expression. If compiler founds a variable of nullable type then the compiler will allow to access the variable.

Simple example:

When we accessing a nullable type of String without safe cast it will give compile time error.

var string: String? = "Hi"  
    print(string.length) // Compile error 
 
//using smart cast

fun main(args: Array<String>){  
var string: String? = "Hi"  
    if(string != null) { // smart cast  
print(string.length) // It works now!  
    }  
}  

//Output:
2

We can also use is or !is for checking the variable, so that the compiler tracks this information and internally cast the variable to target type. This is usually done inside the scope if is or !is returns true.

Simple example:

//use of is for smart cast
fun main(args: Array<String>){  
val obj: Any = "Hi! Android"  
    if(obj is String) {  
                // No Explicit Casting needed.  
println("String length is ${obj.length}")  
    }  
}

//Output:
String length is 11

//use of !is for smart cast
fun main(args: Array<String>){  
val obj: Any = "Hi! Android"  
    if(obj !is String) {  
println("obj is not string")  
  
    } else  
    // No Explicit Casting needed.  
println("String length is ${obj.length}")  
}  

//Output:
String length is 11

Unsafe and Safe Cast Operator

as: unsafe cast operator

When its not possible to cast variable and an expression is thrown, this is called as unsafe cast. The unsafe cast is performed by the infix operator as.

Simple example:

fun main(args: Array<String>){ 
    val str1: String = "Hi! Android"
    val str2: String = str1 as String      // Works 
    println(str1) 
}

//Output:
Hi! Android

as?: safe cast operator

Kotlin language provides a safe cast operator as? for safely casting to a type. It returns a null if casting is not possible and not throw a ClassCastException exception.

Simple example:

fun main(args: Array<String>){ 
  
    var str1: Any = "Hi! Android"
    val str2: String? = str1 as? String     // it will work
    str1 = 11
    // type casting not possible, hence returns null to str3 
    val str3: String? = str1 as? String     
    val str4: Int? = str1 as? Int          // it will work
    println(str2) 
    println(str3) 
    println(str4) 
} 

//Output:

Hi! Android
null
11

elvis (?:) operator

This operator is used to return the non null value even when the conditional expression is null. Also, It is used to check the null safety of values.

Simple example:

fun main(args: Array<String>){  
  
var str: String? = null  
var str2: String? = "Hi! Android"  
var len1:  Int = str ?.length ?: -1  
var len2:  Int = str2 ?.length ?:  -1  
  
println("Length of string 1 is ${len1}")  
println("Length of string 2 is ${len2}")  
}  

//Output:
Length of string 1 is -1
Length of string 2 is 11

For further reading, please visit Kotlin for Beginners – Part 4: Collections and related concepts

 

 

 

 

 

Alright, lets now look at some more topics related to Kotlin programming, namely Flow of Control, Functions, Arrays

Kotlin – if expression

Conditional statements or if-else statement is written in Kotlin in a different manner.

There are mainly 3 ways of writing if – else expression:

  • if – else
  • if – else if – else ladder
  • nested if

Kotlin if-else expression

fun main(args: Array <String>) {  
        val number1 = 4 
        val number2 = 2  
        val finalResult = if (number1 > number2) {  
            "$number1 is greater than $number2"  
        } else {  
            "$number1 is smaller than $number2"  
        }  
        println(finalResult)  
} 
//Output
4 is greater than 2

Kotlin if-else if-else ladder expression

fun main(args:  Array <String>){                     
val num = 2                   
val result = if(num>0) {             
        "$num is positive number"                     
        } else if(num<0){                                
        "$num is negative number"                    
        } else {                       
        "$num is zero"                   
        }                         
          println(result) 
}

Kotlin nested if expression

fun main(args: Array<String>) {  
    val number1 = 5  
    val number2 = 10  
    val number3 = 15  
    val finalresult = if (number1 > number2){  
        val maxnumber = if(number1 > number3){  
            number1  
        }else{  
            number3  
        }  
        "if "+maxnumber  
    }else if(number2 > number3){  
        "else if"+number2  
    }else{  
        "else "+number3  
    }  
    println("$finalresult")  
}

Kotlin – when expression

In this language, ‘when’ is used in place of ‘switch’ serving same purpose.

Simple example:

fun main(args: Array<String>){  
    var days = 7
    var day = when(days) {  
        1 -> "Monday"  
        2 -> "Tuesday"  
        3 -> "Wednesday"  
        4 -> "Thursday"  
        5 -> "Friday"
        6 -> "Saturday"
        7 -> "Sunday"  
        else -> "Invalid day name"  
    }  
    println("You entered $day")  
}  

//Output:
You entered Sunday

when without expression

fun main(args: Array<String>){ 
      var days = 7 
      when(days) { 
      1 -> println("Monday")
      2 -> println("Tuesday")
      3 -> println("Wednesday")
      4 -> println("Thursday")
      5 -> println("Friday")
      6 -> println("Saturday")
      7 -> println("Sunday")
      else -> println("Invalid day")
   }
 }

when in multiple statements

fun main(args: Array<String>){  
    var day = 1  
    when(day) {  
        1 -> {  
            println("Monday")  
            println("First day of the week")  
        }  
        2 -> println("Tuesday")  
        else -> println("Other days")  
    }  
}  

//Output:
First day of the week

when and multiple branches

fun main(args: Array<String>){  
    var number = 10
    when(number) {  
        2, 4, 6, 8, 10 ->  
            println("Even number")  
        1, 3, 9, 11 ->  
            println("Odd number")  
        0 ->  
            println("whole number")  
          else -> println("invalid input")  
    }  
} 

//Output:
Even number

when in range

Range is created using ..(double dot) operator and ‘in’ operator is used to check whether the value belongs to a range.

fun main(args: Array<String>){  
    var num = 2 
    when(num) {  
        in 1..5 -> println("Number is in the range 1 to 5")  
        in 6..10 -> println("Number is in the range 6 to 10")  
        else -> println("Not found")  
    }  
}  

//Output:
Number is in the range 1 to 5

Kotlin – loops

for loop

In Kotlin,  for loop is just like a foreach loop in Java/C#  and it is used to iterate a part of program several times. It iterates through arrays, ranges, collections and other things where iterations are there.

Simple example of iterating in an array:

fun main(args : Array<String>) {  
    val employeeid = arrayOf(101,102,103,104,105)  
    for(id in employeeid){  
        println(id)  
    }  
}  

//Output:
101
102
103
104
105

Just like normal for loop in other languages. It is not required to enclose within curly braces { }, if body of for – loop has only one single line of statement.

We can also iterate elements on the basis of index in array.

Simple example:

fun main(args : Array<String>) {  
    val empid = arrayOf(101,102,103,104,105)  
    for(e in empid.indices)  
       println("empid[$e]: "+ empid[e])  
}  

//Output:
empid[0]: 101
empid[1]: 102
empid[2]: 103
empid[3]: 104
empid[4]: 105

while loop

When we need to iterate a part of a program several times till a particular condition is true, we use while loop.

Simple example:

fun main(args: Array<String>){  
    var i = 0 
    while (i<6){  
        println(i)  
        i++  
    }  
}  

//Output:
0
1
3
4
5

do-while loop

In Kotlin, do-while is written similar to normal do-while loop but includes “;”.

Simple example:

fun main(args: Array<String>){  
    var i = 0
    do {  
        println(i)  
        i++  
    }  
    while (i<6);  
}  
//Output:
0
1
2
3
4
5

Jump statements in Kotlin

There are 3 kinds of Jump statements in Kotlin:

  • break
  • continue
  • return

First, lets look at break statement:

fun main(args: Array<String>) {  
    for (i in 1..5) {  
        if (i == 4) {  
            break  
        }  
        println(i)  
    }  
} 

//Output:
1
2
3

In above example, when value of i became equal to 4 and satisfy the if  ( i == 4 ) than the break expression execute and termination  of for loop takes place.

Another kind of break expression is Kotlin labeled break expression. Example given below:

fun main(args: Array<String>) {  
    loop@ for (i in 1..5) {  
        for (j in 1..5) {  
            println("i = $i and j = $j")  
            if (i == 3)  
                break@loop  
        }  
    }  
} 

//Output:
i = 1 and j = 1
i = 1 and j = 2
i = 1 and j = 3
i = 1 and j = 4
i = 1 and j = 5
i = 2 and j = 1
i = 2 and j = 2
i = 2 and j = 3
i = 2 and j = 4
i = 2 and j = 5

In Kotlin, continue statement is used to continue the current flow of the program and skips remaining code at a specified condition. It affects the inner loop only, if present within a nested loop.

fun main(args: Array<String>) {  
        for (i in 1..3) {  
            println("i = $i")  
            if (j == 2) {  
                continue  
            }  
            println("its below if")  
        }  
}  

//Output:
i = 1
its below if
i = 2
i = 3
its below if

We also have labeled continue statement. See the example:

fun main(args: Array<String>) {  
    labelname@ for (i in 1..3) {  
    for (j in 1..3) {  
        println("i = $i and j = $j")  
        if (i == 2) {  
            continue@labelname  
        }  
        println("its below if")  
    }  
 }  
}  

//Output:
i = 1 and j = 1
its below if
i = 1 and j = 2
its below if
i = 1 and j = 3
its below if
i = 2 and j = 1
i = 3 and j = 1
its below if
i = 3 and j = 2
its below if
i = 3 and j = 3
its below if

Kotlin – functions

If you have reached to this point, it shows your committment towards learning Kotlin. Okay, let’s dive deep into Kotlin functions.

Functions in Kotlin are declared using fun keyword. The two kinds are defined here:

  • Standard library function
  • User defined function

Standard library function

Also, known as built-in library functions or pre-defined functions in general case.

Simple example:

fun main(args: Array<String>) {
    val base = 2
    val exponent = 3
    val result = Math.pow(base.toDouble(), exponent.toDouble())
    println("Answer = $result")
}
//Output:
Answer = 8.0

Here, pow() is a library function which returns result of a number till its power (Double value).

User defined function

Its just like any other function created by user. It takes an input, processes it and return its value.

Simple example:

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

//Output:
addition = 5
code after addition

Kotlin – parameterize function

Simple example:

fun main(args: Array<String>){  
   val result = sum(2, 3)  
    print(result)  
}  
fun sum(number1: Int, number2:Int): Int{  
    val add = number1+number2  
    return add  
}  

//Output:
5

Advance topics like Recursion function, default and named arguments, lambdas, high order functions and inline functions will be covered in next series: Kotlin for Intermediate level.

Kotlin – arrays

In Kotlin, Array is mutable in nature with fixed size meaning, we can perform both read and write operations on its elements.

Array constructor

We can declare array constructor with size and init function. The init function is used to return the elements of array along with their index.

Array(size: Int, init: (Int) -> T)

We can also declare array using arrayOf(), intArrayOf(), charArrayOf(), booleanArrayOf(), longArrayOf(), shortArrayOf(), byteArrayOf() functions.

For complete information on Arrays in Kotlin, please visit: Array – Kotlin Programming Language

Array declaration – using arrayOf() function

Simple example:

var myArray1 = arrayOf(1,2,3,4,5)  
var myArray2 = arrayOf<Int>(1,2,3,4,5)  
val myArray3 = arrayOf<String>("John","Michael","Mandy","Raphael","Akoni")  
var myArray4= arrayOf(1, "Amalo","Shanky")

Array declaration – using intArrayOf() function

Simple example:

var myArray5: IntArray = intArrayOf(1,2,3,4,5)

We can also use set and get methods in Kotlin to modify or access particular elements of an array.

The set() function is used to set element at particular index location and get() function is used to get element from specified index.

Simple example:

set() function

fun main(args: Array<String>) {  
val array1 = arrayOf(1,2,3,4)  
    array1.set(0,5)  
    array1[2] = 6   
    for(element in array1){  
println(element)  
    }  
println()     
}  

//Output:
5
2
6
4

get() function

fun main(args: Array<String>) {  
val array1 = arrayOf(1,2,3,4)  
println(array1.get(0))  
println(array1[2])  
println()  
}

//Output:
2
4

Array: Simple example:

fun main(args : Array<String>){
    var array1 = arrayOf(1, 2, 3, 4, 5)
    println("Size of array is: ${array.size}")
}

//Output:
Size of array is: 5

String will be covered in Kotlin for Intermediate level

For further reading, please visit Kotlin for Beginners – Part 3: Exception Handling and Null Safety

Kotlin is a beautiful language with concise code and fast compilation.

Let’s start this journey by the famous saying,

 

A journey of a thousand miles must begin with a single step

Step 1: Install JDK and setup path in the local system environment variable.

You can install the latest JDK by visiting the downloads section at this link: Download

Alternatively, you can download Amazon Corretto : Download

Optional Step: You can setup Kotlin for command line also

You can download Kotlin compiler from GitHub by visiting following link: Download

 

You can choose anyone out of this

Now, extract the zip file to C:\Program Files. Add the kotlinc\bin directory to your command line path.

 

Then, for Windows, open Control Panel -> System -> Advanced System Settings -> Environment Variables

 

After opening Environment Variables, click on Edit Path in System Variables

 

 Next, paste the copied path of kotlinc bin directory in New

 

And you’re good to go

Step 2: Install an IDE

You need to install an IDE to run Kotlin programs. Some of the available IDEs are:

 

For IntelliJ IDEA setup, look for IntelliJ IDEA Setup for Java and Kotlin

For Android Studio setup, look for Android Studio Setup

 

Kotlin – First Program

 

fun main(args: Array<String>) {  
    println("Hello! Android Resource!")  
}  

Here, we can see that main is a function in Kotlin. Functions are a combination of statements to perform a particular task. The main () function that takes Array<String> as a parameter and returns unit. It means unit does not return any value. As in Java, C, C++ etc – main function is the entry point for a program. Here, the second line prints output to the console : println ()

Output:

 

Hello! Android Resource

 

Kotlin – Variables

variable refers to a memory location that stores some data in it. It has a name and an associated type. The type of a variable defines the range of values that the variable can hold and the operations that can be done on them.

In Kotlin, a variable is declared using keyword val and var.

 

  • val is an immutable variable: Its value cannot be changed.
  • var is a mutable variable: Its value can be changed.

 

val max = 100 
max = 99 //Error 
var name ="Kotlin" 
name = "Java" //execute perfectly 

So, how does Kotlin compiler check which one is String and which one is Int? Here comes the concept of Type Inference

Surely, If we want, we can also explicitly specify the type of variable during declaration.

 

val max:Int = 100
var name:String ="Kotlin"  

 

Kotlin – Data Types

Data type is a broad term used to define the type of data. Every language has different data types.

Kotlin language has variables as objects so that member functions can be called on any variable.

It has 5 built-in data types:

 

  • Number: It holds only integer and float type variables. e.g. byte, short, int, long, float, double
  • Character: It is represented by char keyword, represented by single quotes( ‘char’ ).
  • Boolean: It is represented by boolean, contains values either true or false.
  • Array: It is represented by Array class, created using arrayOf( ), which is a library function and Array( ) constructor. Array has get( ), set( ) functions, size property and some other useful member functions.
  • String: It is represented by String class, also, the elements in the string cannot be changed.

Code for Data Types:

 

// Integer
val rollno = 101

// Float
val point = 132.56

// Char
val grade = 'A'

// Boolean
val result = true

// Array
// Creating array using library function arrayOf()
val  rollno = arrayOf(101,102,103,104,105)  
val firstRollno = rollno[0]  
val lastRollno = rollno[rollno.size-1]

//Creating array using Array() constructor
val rollno = Array(5, { i -> i * 3 }) //rollno[0,3,6,9,12]  

//String
val blog ="Android Resource"

 

Kotlin – Operators

There are 6 types of operators available in Kotlin:

 

  • Arithmetic operators: + , -, *, /, %
  • Relational operators: <, >, >=, <=, ==, !=
  • Assignment or shorthand operators: -=, +=, *=, /=, %=
  • Unary operators: +, -, ++, –, !
  • Bitwise operators: shr, shl, ushr, and, or, xor, inv( )
  • Logical operators: &&, || , !

Arithmetic operators

 

fun main(args : Array<String>) {  
var a=4;  
var b=2;  
println(a+b);  
println(a-b);  
println(a*b);  
println(a/b);  
println(a%b);  
}  

//Output:
6
2
8
2
0

Relational Operators

 

// Relational Operators
fun main(args : Array<String>) {  
    val a = 4  
    val b = 2  
    val min = if (a < b) {  
        println("a is smaller than b.")          
    } else{  
        println("b is smaller than b.")  
    }  
    println("min = $min")  
}  

Assignment or Shorthand Operators

 

// Assignment Operators
fun main(args : Array<String>) {  
    var a =4
    var b =2   
    println("a+=b :"+ a)  
    println("a-=b :"+ a)   
    println("a*=b :"+ a)  
    println("a/=b :"+ a)  
    println("a%=b :"+ a)  
}  
//Output
a+=b :6
a-=b :2
a*=b :8
a/=b :2
a%=b :0

Unary Operators

 

// Unary Operators
fun main(args: Array<String>){  
    var a=4
    var b=2  
    println("+a :"+ +a)  
    println("-b :"+ -b)  
    println("++a :"+ ++a)  
    println("--b :"+ --b)    
}  
//Output
4
-2
5
1

Bitwise Operators

 

//Bitwise operators
fun main(args: Array<String>){  
    var a=4
    var b=2  
    
    println("a.and(b): "+a.and(b))  
    println("a.or(b): "+a.or(b))  
    println("a.xor(b): "+a.xor(b))  
}  
//Output
a.and(b): 2
a.or(b): 4
a.xor(b): 2

Logical Operators

 

//Logical Operators
fun main(args: Array<String>){  
    var a=4
    var b=2  
    var c= 3  
    var flag = false  
    var result: Boolean  
    result = (a>b) && (a>c)  
    println("(a>b) && (a>c) :"+ result)  
}  
//Output
(a>b) && (a>c) : true

 

Kotlin – Input/Output

In Kotlin, the input is taken as by using readLine( ) or Scanner object:

 

// Using readLine()
fun main(args: Array<String>) {  
    println("Enter your name")  
    val name = readLine()  
    println("Enter your rollno")  
    var rollno: Int =Integer.valueOf(readLine())  
    println("Your name is $name and your rollno is $rollno")  
}  
//Output
Enter your name
Sam
Enter your rollno
9
Your name is Sam and your age is 9

// Using Scanner class
import java.util.Scanner  
fun main(args: Array<String>) {  
    val read = Scanner(System.`in`)  
    println("Enter your rollno")  
    var rollno = read.nextInt()  
    println("Your rollno is "+rollno)  
}  
//Output
Enter your rollno
9
Your rollno is 9

 

Kotlin – Comments

Two types of comments are there in Kotlin:

 

  • Single line comment
  • Multi line comment

 

// Single line comment
fun main(args: Array<String>) {  
// statement for printing information on the console 
   println("Hello Android Resource")  
}

// Multi line comment
fun main(args: Array<String>) {  
/* statement for 
   printing information 
   on the console  */  
   println("Hello Android Resource")  
}   

For further reading, please visit Kotlin for Beginners – Part 2: Flow of Control, Functions, and Arrays

 

WTF! I don’t even know Java completely

Don’t worry if you’re still struggling with Java while developing your apps. Like most of the people, you must have become overwhelmed while writing code. The good news is Android Resource has come with Kotlin for beginners – A series like no other.

We will explain everything you need to know about Kotlin, right from basics to advanced and also give you insights about real-world apps.

Java developer who started learning at the age of 15!

Let’s look at the agenda for the series:

  1. Kotlin for Beginners – Part 1: Environment Setup, Variables, Data Types, Operators, Comments
  2. Kotlin for Beginners – Part 2: Flow of Control, Functions, and Arrays
  3. Kotlin for Beginners – Part 3: Exception Handling and Null Safety
  4. Kotlin for Beginners – Part 4: Collections and related concepts
  5. Kotlin for Beginners – Part 5: OOPS
  6. Kotlin for Beginners – Part 6: Miscellaneous concepts

After all of the above concepts, we will start for Kotlin for Android Intermediate series which will help you understand how to use Kotlin while developing apps. Stay tuned for more cool stuff.

Those who don’t like Java will fall in love with it.

Let me start this amazing post about basic Kotlin programming by first thanking Google for bringing out this amazing programming language to the developer community.

Years have passed and yet many developers are there who don’t like Java at all maybe because of any reason. For them, Kotlin is here to rock your life.

So let’s start this journey by pondering over the first natural question:

What is Kotlin?

According to Wikipedia.org, Kotlin is a cross-platform, statically typed, general-purpose programming language with type inference. So it basically means, with Kotlin, you can develop applications for multiple platforms like iOS and Android. Kotlin variable types are declared explicitly and we can determine them on the compilation stage.

In other words, Kotlin is an open-source programming language developed mainly for the development of Android Applications and is an alternative to Java.

Why Kotlin?

Kotlin has an improved design as compared to Java and is based on Java Virtual Machine(JVM). We can talk a lot through Java vs Kotlin but Kotlin seems to be a near sister of Java.

Let’s look at what advantages are there with Kotlin one by one. The exhaustive list is compiled by Charles Kincy,

  • Inherent null-safety
  • Infix operators (which allow easy construction of DSLs)
  • Coroutine programming
  • Extension methods to allow better object encapsulation on code you don’t own.
  • Functions as a first-class object
  • Numerous helpful object-functional extensions (like Any.apply)
  • Simplified POJO construction via data classes and properties as a first-class object.
  • Standard linter for uniform coding style.

You can visit his complete answer at https://www.quora.com/How-does-Kotlin-compare-to-Java

But why Google is supporting Java even with the advent of Kotlin? Primarily, of two reasons:

  • While the code of Kotlin is easy as compared to Java and has fewer complexities but the extension methods can break encapsulation and this can lead to other problems.
  • Kotlin is not mature and completely reliable as compared to Spring and other frameworks of Java for enterprises involved in medium-scale development.

Yet Kotlin seems to be evergrowing in terms of the number of Android Apps being converted to it on a daily basis and similarly more and more developers are looking to adopt it.

History of Kotlin

Kotlin was developed by a world-renowned IDE producer Jet Brains Inc. in July 2011 under Project Kotlin.

The project team was very curious to name it Kotlin after Kotlin Island, near St. Petersburg

First official release was Kotlin v1.0 on 15 February 2016 and this was the first official stable release.

At Google I/O 2017, Google announced its support for Kotlin.

Google announced that the Kotlin programming language is now its preferred language for Android app developers in May 2019.

Thanks for the read!

For the beginner introduction to Kotlin, please visit : Let’s start Kotlin programming