Sunday 6 December 2020

Kotlin - Collection Partition function

Splits the original array / collection into pair of lists, where first list contains elements for which predicate yielded true, while second list contains elements for which predicate yielded false.  
Please refer the below Code Snippet for the details.

val employeeList = listOf(
EmployeeInfo("HB100", "Ragavan A", 30),
EmployeeInfo("AX782", "Peter J", 54),
EmployeeInfo("ZD242", "Karlos V", 56),
EmployeeInfo("CD902", "Ismail N", 24)
)

val (ageAbove50, ageBelow50) = employeeList.partition { it.eAge > 50 }
println("\nEmployee List: $employeeList")
println("\nAge Above 50: $ageAbove50")
println("\nAge Below 50: $ageBelow50")

/*Since it returns as pairs, If we want to ignore the other condition i.e. 
ageBelow50 employees use _*/
val (ageAbove50Plus, _) = employeeList.partition { it.eAge > 50 }
println("\nAge 50+: $ageAbove50Plus")

Output:

Employee List: 
[EmployeeInfo(eId=HB100, eName=Ragavan A, eAge=30), 
EmployeeInfo(eId=AX782, eName=Peter J, eAge=54), 
EmployeeInfo(eId=ZD242, eName=Karlos V, eAge=56), 
EmployeeInfo(eId=CD902, eName=Ismail N, eAge=24)]

Age Above 50: [EmployeeInfo(eId=AX782, eName=Peter J, eAge=54), 
EmployeeInfo(eId=ZD242, eName=Karlos V, eAge=56)]

Age Below 50: [EmployeeInfo(eId=HB100, eName=Ragavan A, eAge=30), 
EmployeeInfo(eId=CD902, eName=Ismail N, eAge=24)]

Age 50+: [EmployeeInfo(eId=AX782, eName=Peter J, eAge=54), 
EmployeeInfo(eId=ZD242, eName=Karlos V, eAge=56)]

Sunday 17 May 2020

lateinit Vs by lazy


Both "lateinit" and "by lazy" are Kotlin Property initializers.

lateinit:
  • Use it with mutable variable [var]
  • Allowed with only non-nullable data types
  • This modifier is not allowed on properties of primitive types
  • It is a promise to compiler that the value will be initialized in future.
  • If you try to access lateinit variable without initializing it then it throws UnInitializedPropertyAccessException.
by lazy:
  • Lazy initialization was designed to prevent unnecessary initialization of objects.
  • Your variable will not be initialized unless you use it.
  • It is initialized only once. Next time when you use it, you get the value from the memory.
  • It is thread safe (It initializes in the thread where it is used for the first time. Other threads use the same value stored in the cache).
  • The variable can only be val.
  • The variable can only be non-nullable.
class Basic {
    private lateinit var strMsg: String
    private val strMsg1: String by lazy {
        println("Lazy Initializing - Variable born")
        return@lazy "Tester"
    }

    fun initBasic() {
        //Late Initialization - Check
        println("strMsg initialization status is ${::strMsg.isInitialized}");
        strMsg = "Testing"
        println("strMsg value is $strMsg, now the initialization status is ${::strMsg.isInitialized}");

        //Lazy Initialization - Check
        println("strMsg1 value is ${strMsg1}");
    }
}

fun main(ar: Array<String>) {
    Basic().initBasic()
}

Console Output:

strMsg initialization status is false
strMsg value is Testing, now the initialization status is true
Lazy Initializing - Variable born
strMsg1 value is Tester

Monday 27 April 2020

Kotlin Generic function & Infix

Generics are the powerful features that allow us to define classes, methods and properties which are accessible using different data types while keeping a check of the compile-time type safety.

A generic type is a class or method that is parameterized over types. We always use angle brackets (<>) to specify the type parameter in the program.

Advantages of generic –
  1. Type casting is evitable- No need to typecast the object.
  2. Type safety- Generic allows only single type of object at a time.
  3. Compile time safety- Generics code is checked at compile time for the parameterized type so that it avoids run time error
Infix:  This is the Kotlin keyword used before the function and this enables us to call the methods without any dot and parenthesis.  This increase the code readability in a general way (as like as speaking language :-) ).

Rules for the Infix:
  1. All Infix functions are need to be Extension function or member function.
  2. It must accept only one param and no default value is permitted.
  3. It must have "infix" keyword before to the function.  
Lets see some code Snippet: 
  1. Just created a demo data class 
  2. Two Generic and extension functions (Extension of List) and in that one of them is infix, you can see the above rules is applied.  
data class Demo(val id: String, val name: String)

fun <T> List<T>.updateObjWith(other: List<T>) = this + other

infix fun <T> List<T>.updateWith(other: List<T>) = this + other

Calling the non-infix generic function:
  1. Here you can see the list objects created for different types
  2. Updated the object with the some more contents using the updateObjWith(<T?) method 
fun main() {
    val myPlaces = listOf<String>("Chennai", "Puducherry")
    val myPlayers = listOf<Demo>(Demo("123EAX", "Ragavan"), Demo("989XEA", "Rajeevan"))
    val myNumbers = listOf<Int>(1, 2, 3, 4, 5)

    val updatedPlayers: List<Demo> = myPlayers.updateObjWith(listOf(Demo("325EUV", "Manirathnam")))
    updatedPlayers.forEach { println(it) }

    val updatedPlaces: List<String> = myPlaces.updateObjWith(listOf("Madurai"))
    updatedPlaces.forEach { println(it) }

    val updatedNumbers = myNumbers.updateObjWith(listOf(10, 9, 8, 7, 6))
    updatedNumbers.forEach { println(it) }
}

Calling via Infix function: Code will be in more readable form.

fun main() {
    val myPlaces = listOf<String>("Chennai", "Puducherry")
    val myPlayers = listOf<Demo>(Demo("123EAX", "Ragavan"), Demo("989XEA", "Rajeevan"))
    val myNumbers = listOf<Int>(1, 2, 3, 4, 5)

    val updatedPlayers = myPlayers updateWith listOf(Demo("325EUV", "Manirathnam"))
    updatedPlayers.forEach { println(it) }

    val updatedPlaces = myPlaces updateWith listOf("Madurai")
    updatedPlaces.forEach { println(it) }

    val updatedNumbers = myNumbers updateWith listOf(10, 9, 8, 7, 6)
    updatedNumbers.forEach { println(it) }
}

Sunday 5 April 2020

Singleton - Java vs Kotlin

Singleton is a widely used design pattern in our programming, because the single instance or object reference has been used to accessing their properties and that instance remains through out the  application session.

Now we can see how it will be implemented in Java and Kotlin.

Singleton Using Java:

public final class Singleton {
    private static final Singleton INSTANCE = new Singleton();
    public String property1;

    private Singleton() {
    }

    public static Singleton getInstance() {
        return INSTANCE;
    }

    public String getInfo() {
        return "SingleInfo";
    }
}

Points to be remembered on creating the Singleton class using Java.
  1. Class need to be final, in order to avoid this class to be inheritance by other.
  2. Constructors are need to be private
  3. private, static and final instance have to instantiated.
Accessing the properties and methods will be as follows.

String property1 = Singleton.getInstance().property1;
String info = Singleton.getInstance().getInfo();

Singleton in Kotlin: Here it is very crazy in kotlin, the below things does the job.

object Singleton {
    var property1: String? = null
    val info: String
        get() = "SingleInfo"
}


val property = Singleton.property1
val info = Singleton.info

Happy Coding :-)

Monday 27 January 2020

Kotlin Complete References

The below reference links are enough for us to get a good amount of knowledge on Kotlin Programming. 


📌 Highly Recommended   |  
🔖 Recommended

Kotlin Cheat Sheet:
📌 Kotlin Academy

Kotlin Videos:
General Videos 
📌 Smarthed Kotlin Playlist
🔖 Telusko Kotlin Playlist
📌 CodingWithMitch for Kotlin Coroutines 
 
Videos by Dr. Venkat Subramaniam 
📌 Kotlin for Java Programmers 
🔖 Kotlin for Java Programmers 
📌 Kotlin Programming
📌 Functional Programming in Kotlin
🔖 Exploring Coroutines in Kotlin

Videos by Hadi Hariri
📌 Kotlin Beyond the basis
📌 Functional Programming with kotlin
📌 Kotlin Coroutines

Web Tutorials:
📌 Programiz
📌 GeeksForGeeks
🔖 TutorialKart