Thursday, 23 April 2020

Kotlin : Null Safety Operators (Post 20)

Hi ,

I am here again to share another important topic of Kotlin , which is  null safety . In Kotlin , it is defined to avoid NullPointerException .
There are following types of Null Safe Operators which can be used in our code to avoid NPE :


  • Safe Call (?.)
  • Safe Call with let ( ?.let)  
  • Elvis Operator (?:)
  • Non-null Assertion Operator (!!)

Safe Call (?.) 


It can be used when null value will not affect the programming flow . 
Variable will return the value if not null else return null value. 

var name : String? = null
var name2 : String = "Hello"
        
println("Length of NAME:"+ name?.length) //using safe call operator for nullable
println("Length of NAME2:"+ name2.length)

Output :


Length of NAME:null
Length of NAME2:5

Here we can see that Name2 length is 5 , but name is having null value so length is also returning null.

======================================================================

Safe Call with let ( ?.let)  

Executes the let block only when , if the variable value is NOT NULL

var name : String? = null
var name2 : String = "Hello"

name?.let {  println("Length of NAME:"+ name?.length) }

name2.let {   println("Length of NAME2:"+ name2.length) }

Output :


Length of NAME2:5

Since name is having null value so for that let block will not execute , so it will not print the statement , only name2 , let statement will execute and show the output.

========================================================================

The Elvis Operator 

It is represented by a question mark followed by a colon: ?: and it can be used with this syntax:
first operand ?: second operand
If first operand isn't null, then it will be returned. If it is null, then the second operand will be returned. This can be used to guarantee that an expression won't return a null value, as you'll provide a non-nullable value if the provided value is null.

var name: String? = null
        
val length = name?.length ?: -1
println("Length of NAME: " + length)

Output :


Length of NAME: -1

Here value of name is null so last statement is executed !

========================================================================

Non-null Assertion Operator(!!) 

This can be used when it is sure that variable value must not be NULL , it will throw NullPointerException , when variable is found Null .

var name : String? = null
var name2 : String = "Hello"

println("Length of NAME2:"+ name2!!.length)
println("Length of NAME:"+ name!!.length) //this will throw NPE
       

Output :

Length of NAME2:5

Unable to start activity ComponentInfo: kotlin.KotlinNullPointerException

As operator explains that throw NPE in case variable will contain null value , so when getting the length of name variable , which is having null value , it is throwing NullPointerException.

So this is the basic practice of how Null Safety has been handled in Kotlin . I will share another post in this series very soon , till then Happy Coding 😀😀









Kotlin : filter & map (Post 19)

Hello All,

Today I am going to share 2 another important operations that are "filter" & "map" ,

Filter : This is used to apply a condition , on collections elements and get the resultant collections data , then there "filter" is used.

Map : This is used to transform all the elements of collections data

 override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
       
        var myList =  mutableListOf<Int>(34 , 6 , 29 , 15 , 65 , 9 , 12 , 42)
        var myEvenList = myList.filter { it%2 == 0 }
        for(num in myEvenList){
            println(num)
        }
         println("Double list : ")

        var myDoubleList = myEvenList.map { it*2 }
        for(num in myDoubleList){
            println(num)
        }
    }

Output :

34
6
12
42

Double list : 
68
12
24
84

Here , we can see that I have added the condition to get even number from the myList , which is returning myEvenList , then I applied the map condition for getting the double numbers of all the elements of myEvenList , which we are getting in myDoubleList .

Now take one example of Employee Data class :


override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
     
        var myList = listOf<Employee>(
            Employee(101,"Alen"),
            Employee(102,"Harrey"),
            Employee(103,"John"),
            Employee(104,"Sam"),
            Employee(105,"Alice"))
        var nameList: List<String> = myList.map{it.empName}

        for(name in nameList){
            println(name)
        }
        println("Initial List : ")
        var initialList = nameList.filter{ person -> person.startsWith("A")}
        for(num in initialList){
            println(num)
        }
    }
    class Employee (var empId: Int, var empName: String) {
    }

Output :
Alen
Harrey
John
Sam
Alice

Initial List : 
Alen
Alice


Here I have used one list , which is containing the list of Employees ,
then in nameList , all the names are fetched using map()
then from nameList , all the names are fetched starting with 'A'  , returning the initialList .

Hope this will help to understand these two important topics of Kotlin. Will share another interesting topic in my next post , till then Happy Coding 😀😀

Kotlin : Collections Set & HashSet (Post 18)

Hi  ,

Here I am again going to share how Set and HashSet are working in Kotlin .

Let's take a look first what is Set and HashSet :

Set : Always contains unique elements

HashSet : Always contains unique elements , and output sequence is not guaranteed .

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        
        /**
         * Set -> contains unique elements
         * HashSet -> contains unique elements ,but sequence is not same
         */
        //immutable , fixed size , Read only operation
        var mySet = setOf<Int>(13, 4, 32 , 2, 2, 2 , 5, 8 , 13)
        for (element in mySet) {
            println("Immutable Elements: $element ")
        }

        //mutable ,not fixed in size ,Read & Write Operations
        var mutableSet1 = hashSetOf<Int>()
        var mutableSet = mutableSetOf<Int>(13, 4, 32 , 2, 2, 2 , 5, 8 , 13)
        mutableSet.add(56)
        mutableSet.remove(5)

        for (element in mutableSet) {
            println("mutable Elements : $element")
        }
    }

Output :

Immutable Elements: 13 
Immutable Elements: 4 
Immutable Elements: 32 
Immutable Elements: 2 
Immutable Elements: 5 
Immutable Elements: 8 
mutable Elements : 13
mutable Elements : 4
mutable Elements : 32
mutable Elements : 2
mutable Elements : 8
mutable Elements : 56

Here we can see the for Immutable section

  •  all the elements sequence is same as input , 
  • the duplicate elements has been removed ! 

But for mutable section :

  • The duplicates elements are removed 
  • Input Elements sequence have been changed
  • Element 5 has been removed using .remove() operation
  • Element 56 has been added using .add() operation
So this is the simple example of Set and HashSet in Kotlin , this will help to get a basic understanding. In next post I will again explore 1 interesting topic in Kotlin , till then Happy Coding 😀😀




Tuesday, 21 April 2020

Kotlin : Collections Map & HashMap (Post 17)

Hi ,

Again I am here to share one another topic in Kotlin series i.e. Map & HashMap

So as we all know that how map & hashmap algorithm , how they save the elements using keys .
In the same way here in Kotlin , the elements are saved using keys , also elements modifications are also done using keys.

Now , after talking so much for this , let's directly move to technical stuff :

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
       
        //immutable , fixed size , Read only operation
        var myMap = mapOf<Int, String>(13 to "Android", 4 to "iOS", 32 to "Flutter")
        for (key in myMap.keys) {
            println("Elements with Key: $key => ${myMap[key]}")
        }

        //mutable ,not fixed in size ,Read & Write Operations
        var mutableMap1 = hashMapOf<Int, String>()
        var mutableMap2 = HashMap<Int, String>()
        var mutableMap = mutableMapOf<Int, String>()
        mutableMap.put(13, "android")
        mutableMap.put(3, "iOS")
        mutableMap.put(6, "flutter")

        //remove
        mutableMap.remove(3) //removing
        mutableMap.put(3, "React Native") //adding
        for (key in mutableMap.keys) {
            println("mutable Elements with Key: $key => ${mutableMap[key]}")
        }
    }

So here we can see that , I have added two types of maps one is immutable and another one is mutable .

In both types of maps , I have added the elements on the basis of keys
and in mutable type of maps I have also modified the elements using keys.

That's a small demo foe how maps and hashmaps will work with Kotlin. In next post I will share the functionality of  Set & HashSet , till then Happy Coding 😀😀

Kotlin : Collections Mutable & Immutable with List & Array List (Post 16)

Hi ,

Let's take a look , how collections work in Kotlin . There are basically 2 types of Collections :

Mutable & Immutable

Immutable :  Read Only Operations , Fixed Size 

  • Immutable List : listOf
  • Immutable Map : mapOf
  • Immutable Set: setOf
Mutable :  Read  & Write Operations , Not Fixed Size 

  • Mutable List :  ArrayList , ArrayListOf , mutableListOf
  • Mutable Map : HashMap , HashMapOf, mutableMapOf
  • Mutable Set:    HashSetOf , mutableSetOf

     
Here I am sharing a basic example of List & ArrayList , to understand how can we use it :

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        //immutable , fixed size , Read only operation
        var myList  =  listOf<String>("Android" , "iOS" , "Flutter")
        for(element in myList){
        println(element)
        }

        //mutable ,not fixed in size ,Read & Write Operations
        var mutableList1  =  arrayListOf<String>()
        var mutableList2  =  ArrayList<String>()
        var mutableList  =  mutableListOf<String>()
        mutableList.add("android") //0
        mutableList.add("iOS") //1
        mutableList.add("flutter") //2

        //remove
        mutableList.remove("iOS") //removing @ 1 index
        mutableList.add("React Native") //adding @ 1 index
        for(element in mutableList){
            println(element)
        }
    }

Output : 
Android
iOS
Flutter

android
React Native
flutter

Explaination: 
Here we can see that with immutable list , we can only READ the elements  , but with mutable list I have removed one element from index 1 and then add another element at index 1 .
Also I have shared all the types of mutable list which we can use it in our code  , let's take a look what are the types of these array lists :

 var mutableList1: ArrayList<String> =  arrayListOf<String>()
 var mutableList2: ArrayList<String> =  ArrayList<String>()
 var mutableList: MutableList<String> =  mutableListOf<String>()

Here one thing is noticable that  MutableList<String> , is also implemented by ArrayList<String>

So that was very basic explanation of List / ArrayList , which will help to understand the functionality. In next post I will share for Map and Set , till then Happy Coding 😀😀


Kotlin : "with" & "apply" keywords (Post 15)

Hi  ,

Again I am sharing two basic and import keywords that are : "with" & "apply" .Both keywords are part of Kotlin Standard Library

Let's take a look :

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        //with keyword
        with(Mobile()){
            os = "Android"
            version = "10.0.0"
        }

        // apply keyword
        Mobile().apply{
            os = "Android"
            version = "10.0.0"
        }.checkStatus()
    }

    /**
     * Mobile class
     */
    class Mobile {
        var os: String = ""
        var version: String = ""

        fun checkStatus() {
            println("I am in Mobile class!")
        }
    }


Here we can see that we can assign the value to the variables of mobile class using with and apply keyword .

With the help of apply keyword we can also call the member function of that class.

That's all for this post , I will again share some new concept of Kotlin Language  , till then Happy Coding 😀

Sunday, 19 April 2020

Kotlin : "it" keyword (Post 14)

Hi ,

Let's discuss the "it" keyword, with lambda expression.

it keyword is basically is used as implicit the single parameter.

If any lambda expression is using one parameter , then it can be replaced with "it" keyword .

Here is a simple example for understanding : 
override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        getLength("Android", { a -> a.length })
        getLength("Android", { it.length })
    }
    /**
     * High Level Functions
     */
    fun getLength(a: String, myExp: (String) -> Int) {
        println(myExp(a))
    }

Here we can see that "a" argument is used to get the length of "a" lambda expression is used.
So it can be replaced as  "a -> a" to "it" , and it is only applicable for single parameter.

That's all for this post. Will share another post soon , till then Happy Coding :)


Advanced Kotlin Coroutines : Introduction

 Hi,  Today I am unwraping the topic in Kotin world i.e. Coroutine . If you want to get started with Kotlin coroutine and ease your daily de...