Kotlin - Android

Basic of Kotlin to get started in android Part-2

In my last tutorial, we have learned the basic introduction about Kotlin. Kotlin is inspired by C#, Groovy, and Scala language. I recommend you to please check my last post-Basic of Kotlin to get started in android part-1.

Google I/O 2017 announced that Kotlin will be the official language for Android development. This is great news for JetBrains team and all Android developers. Finally, we got the new awesome language to use in the android-building.  Thanks, Google to take care android very strongly and to frequently update android features to provide the better user experience.

OK let’s start to understand this new awesome language kotlin.

Variables in Kotlin

Variables in kotlin are similar to Java in their scope. Variable in Kotlin is mostly preferred the immutable because of its thread safe. One interesting thing in kotlin is that we do not need to declare the object type as long as the compiler can infer it.

So we need to write var and val depend on the type of the variable we want to generate. Even Kotlin also provide an option to define the variable type explicitly. Kotlin automatically typecast as those.

One more interesting thing in Kotlin is that we do not need to write the semicolon at end of the statement. All those are boilerplate code in old programming which is removed in Kotlin.

Here is the few example to understand.

class KotlinVariableTest1 {

    // global variables
    private var varName : Int = 5
    var varName2 : String = "Hello"  // default will be public
    
    var varName3 = 10
    var varName4 = "Hello dude!"

   

    fun varDeclarationLocalTest(){
        // local variable
        var varLocName1 : Int
        varLocName1 = 20

        varName3 = varLocName1;  // assign local to global

        varName4 = varLocName1.toString()  // assign integer to string


    }
}

Functions in Kotlin

Function in Kotlin is similar to method in Java.  Only thing is different in kotlin is method represents predefined fun keyword. Every fun is by default public in Kotlin. A function could be return type and not be, it depends on our requirement. Everything is similar to in java for example argument parameter, the only syntax will differ in Kotlin.

Let’s see all different type of function we can define and how to call one function inside the function?

class KotlinFunctionTest2 {

    // function with no param

    fun functionTest1(){
        print("Function has not param and no return type")
    }

    fun functionTest2(): String {
        var msg = "I am retuning String"
        return msg
    }

    // default any function will be public even you can write access also
    public fun functionTest3(param1: Int, param2: Int): Int {
        var multiply = param1 * param2
        print("Multiply result: $multiply")
        return multiply
    }

    // function with different param with no return

    fun functionTest4(param1: Int, param2: String){
        print(param2)
        println(param1)
    }

    // function calling inside

    fun functionTest5(){
        functionTest4(5, "Hello")
        functionTest3(4, 5)
    }
}

Conditional Statement 

If I am talking about conditional statement then I am sure you understood about the if -else, while, do- while, and for the loop. One thing I did not mention here switch condition. So switch condition is no more with Kotlin. In place of the switch, we can use when condition. Let’s see with an example how we can use all these conditional statements in Kotlin?

Let’s check first if-else condition in Kotlin. It is almost same like Java.

fun getMaxValueBetweenTwo(a: Int, b: Int) : Int{
        if (a > b){
            return a
        }else{
            return b
        }
    }

But most preferable in Kotlin is like that.

fun getMaxValueKotlin(a: Int, b: Int) = if (a > b) a else b

Let’s see how we can use when condition which is replaced with switch? Kotlin has improved a lot with when condition.

fun getWhatType(a : Int){

        when(a){
            1 -> print("1")
            2-> print("2")
            else -> {
                print("Neither 1 or 2")
            }
        }
    }

Even we can give the range also and any object type to check in cases.

 fun getWhatType(a : Int){

        when(a){
            1,2 -> print("Either 1 or 2")
            in 3..20 -> print("a is in range of 3 ot 10")
            else ->{
                print("None of the above");
            }
        }
    }
fun getWhatTypeCase(obj: Any) {
        when (obj) {
            1 -> println("One")
            "Hello" -> println("Kotlin")
            is Long -> println("Long")
            !is String -> println("Not a string")
            else -> println("Unknown")
        }
    }

and many another way Please check kotlin official site. Ok, Let’s see the while and do- while loop in kotlin.

fun whileLoopTest(){
        val numbers: IntArray = intArrayOf(10, 20, 30, 40, 50)
        var index: Int = 0
        while (index < numbers.size){
            print(numbers[index])
            index ++
        }
    }

This is while loop now lets’s see do- while loop.

 fun doWhileLoopTest(){
        val chars : CharArray = charArrayOf(
                'a', 'b', 'c', 'd'
        )
        var index: Int = 0
        do {
            print(chars[index])
            index ++
        }while (index < chars.size)

    }

Now let’s see how we can use for loop in kotlin. For loop is mostly used for iteration. This is the best iteration of the list of items. In Kotlin we can iterate it in two different ways.

fun forLoopTest1(){
        val numbers: IntArray = intArrayOf(10, 20, 30, 40, 50)
        for (i in numbers.indices) {
            println(numbers[i])
        }
    }

    // in other way you can iterate
    fun forLoopTest2(){
        val numbers: IntArray = intArrayOf(10, 20, 30, 40, 50)
        for ((index, value) in numbers.withIndex()) {
            println("the element at $index is $value")
        }
    }

Great. Awesome Kotlin.

Wrapping up – This is all about the variable declaration, Function and Conditional statement. You can do much more practice with these concepts in deep. I recommended going through the Kotlin official site for more update. In my next tutorial, we will learn other features about class and Object. Here is the link of Basic of Kotlin to get started in android part-3.

Ok Please do subscribe your email to get the updated newsletter of this blog and if you like this post then do not forget to share and comment below.

Happy coding 🙂

0 0 votes
Article Rating

Recent Posts

Hide your production API key or any sensitive data in Android

Hi everyone, In this article, we are going to learn how to hide the production… Read More

2 years ago

How to handle the localisation or multi language support in android with examples?

Hello everyone, Today in this article, we are going to learn about localisation to support… Read More

2 years ago

How to convert any callback to Coroutines and use them in Kotlin Android?

Hello everyone, In this article, we are going to learn something to handle the callback… Read More

2 years ago

Request Permission Launcher with Kotlin in Android

In this article, we are learning about the run time permissions for request permission launchers.… Read More

2 years ago

Implement the SMS User Consent API and SMS Retriever API in Android

Hello everyone. In my last tutorial, we learned about the Jetpack Compose introduction and about applying the… Read More

3 years ago

Jetpack Compose Coroutine flow with LiveData/ViewModel in Android

Hello everyone, In this article, we are going to learn about the Jetpack Compose with… Read More

3 years ago