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.
- Type casting is evitable- No need to typecast the object.
- Type safety- Generic allows only single type of object at a time.
- 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:
- All Infix functions are need to be Extension function or member function.
- It must accept only one param and no default value is permitted.
- It must have "infix" keyword before to the function.
Lets see some code Snippet:
- Just created a demo data class
- 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:
- Here you can see the list objects created for different types
- 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:
Post a Comment