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.
  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) }
}

No comments: