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.
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
Calling via Infix function: Code will be in more readable form.