Updated April 5, 2023
Introduction to Kotlin Generics
In kotlin generic is one of the feature that allows to define the classes, methods and properties that are used to accessed with different types that can be checked at the compile time for all the differences of classes, methods the generic type class or method is declared as the parameterized type and also the type is the instance of generic type with actual type of arguments. It can be declared using the angle brackets like ‘<>’ the generics are mostly used in the collections it holds only the single type of object it does not accept multiple objects.
Syntax
The kotlin language has many default keywords, variables, and other functions for implementing the mobile-based application. Like that kotlin generics is one of the keywords it has been denoted like diamond symbol<> for to declare and utilized it on the application.
fun main(args:Array){
var vars=first(parameters)
---some logic codes depends on the requirement---
}
class first(parameters){
----some logic codes---
}
The above codes are the basic syntax for to implement the generics is defined as the template and it is determined dynamically determined by the kotlin complier so that the datatype is passed as the generic type and the same will be called on the main method.
How does Generics work in Kotlin?
The kotlin a class and a type are used and they called wherever it requires on that package and the same will be passed as the parameter in the other classes methods. In kotlin provides higher order of variable typing and it is referred as the generics types it is the type-safety that allows to hold only single type of object it does not allow to store other object. It has followed with the other features and except the typecasting is not required, the generics code is checked at the compile time and so it can be avoided with any problems at the runtime. When we want to assign the generic type to any of its super type then we can use the keyword like “out” so that it want to assign the other generic type to any of its sub-type then we need to use the keywords like “in” for to referring the input type of the parameters. It has Reified type parameters that allows you to refer at the runtime to the specific types used as the type arguments in the inline function call it does not act as the normal class function because argument types are erased at the runtime.
Examples of Kotlin Generics
Following are the examples are given below:
Example #1
Code:
import java.util.Scanner
class First(id: T){
var id: T = id
init {
this.id= id
println(id)
}
}
fun demos(lst: ArrayList){
for(elm in lst){
println(elm)
}
}
fun examp1(sr1: String,sr2: String, exmp: (String,String) -> String): Unit {
val out = exmp(sr1,sr2)
println(out)
}
fun ArrayList.filterOnCondition(condition: (T) -> Boolean): ArrayList{
val rst = arrayListOf()
for (itm in this){
if (condition(itm)){
rst.add(itm)
}
}
return rst
}
fun main(args: Array){
println("Welcome To My Domain its the first example related to the kotlin generics")
var idInt: First = First(41)
var idString: First = First("41")
println(idString)
val strlst: ArrayList = arrayListOf("Siva","Raman","Sivarman","Arun","Kumar","Arun kumar")
val s: String = strlst[0]
println("Thank you users your input string is: $s")
demos(strlst)
val st1: ArrayList = arrayListOf(23.6f,15.2f,33.7f,44.6f,54.6f)
demos(st1)
try {
val inps = Scanner(System.`in`)
println("Welcome To My Domain its the first example that related to the kotlin higher oder function")
println("Please enter your inputs")
var id1 = inps.nextInt()
println("Your input id is "+id1)
val la: (Int) -> Unit= {sts: Int -> println(sts) }
val inpr = 25 / 5
println(inpr)
}
catch (e: NullPointerException) {
println(e)
} finally {
println("finally block always executed whenever try is executing")
}
println("Have in Nice Day users please try again")
val exmp:(String,String)->String={st1,st2->"$st1 assigned and it will be automatically goes to $st2"}
examp1("First Input","Second Input",exmp)
var lst1 = arrayListOf()
lst1.add("January is the first month")
lst1.add("February is the second month`")
lst1.add("March is the third month")
lst1.add("April is the fourth month")
lst1.add("May is the fifth month")
lst1.add("June is the sixth month")
lst1.add("July is the seventh month")
lst1.add("August is the eigth month")
lst1.add("September is the ninth month")
lst1.add("October is the tenth month")
lst1.add("November is the eleventh month")
lst1.add("December is the twelth month")
var mfl = lst1.filterOnCondition { it.contains("seven") }
val mf2 = { print("Have a Nice day users please continue to spenting your time with us") }
frt(mf2)
}
fun frt(mf2: () -> Unit) {
mf2.invoke()
}
fun samp(inp1: Int, inp2: Int,lamb: (Int) -> Unit){
val result = inp1 + inp2
println(result)
}
Output:
The above example we used kotlin generics basics along with collections and other customized methods used for performing the tasks.
Example #2
Code:
fun main(args: Array){
val strlst: ArrayList = arrayListOf("Siva","Raman","Sivaraman","Arun","Kumar","Arunkumar")
strlst.printValue()
val flist: ArrayList = arrayListOf(33.8f,7.3f,34.7f)
flist.printValue()
Bank()
var bnk= Bank()
bnk.insert(43,"SRBank",34521f)
println("${bnk.name}")
}
fun ArrayList.printValue(){
for(elm in this){
println(elm)
}
}
class Bank {
var id: Int = 0
var name: String = ""
var bnktrnxlimit: Float = 0.toFloat()
fun insert(ac: Int,n: String, am: Float ) {
id=ac
name=n
bnktrnxlimit=am
println("Bank no: ${id} holder :${name} bnktrnxlimit :${bnktrnxlimit}")
}
}
Output:
In second example we used collection concept along with the generic concepts for to store the bank name details.
Example #3
Code:
data class TV(val tvName: String)
class tvBrand(val lst: List) {
fun tvBrand(): List {
return lst.filterIndexed { id, _ -> id % 2 == 1 }
}
}
fun main() {
val lststr = listOf("eAirtec", "Samsung", "Vu")
val rslt: tvBrand = tvBrand(lststr)
println(rslt.tvBrand())
val lstInt = listOf(2, 4, 6, 8, 10, 12)
val rstInt = tvBrand(lstInt)
println(rstInt.tvBrand())
val tvlst = listOf(
TV("eAirtec"),
TV("Samsung"),
TV("Vu"),
TV("Onida"),
TV("Airtel")
)
var out = tvBrand(tvlst).tvBrand()
println(out)
}
Output:
The final example we created and listed the tv lists using the generics types.
Conclusion
In the kotlin language, we used many default classes, methods and variables for to implement the kotlin mobile-based application. Among those generics is one of the type that can be used to perform the operations used by the generic type with the keyword and operators called to the other areas wherever it requires.
Recommended Articles
This is a guide to Kotlin Generics. Here we also discuss the introduction, syntax, and working of generics in kotlin along with different examples and its code implementation. You may also have a look at the following articles to learn more –