Android Programming – Part 10 Kotlin Fundamentals Ⅹ: Generics

Again, quite similar to Java.

A little bit more flexibility can be added to your code by taking advantage of Generics. Just like that Java, you can take advantage of Generics power to boost your coding learning journey and skills!

You must be familiar with generics if you already have some programming experience. And our first code, GenericsSample1.kt, doesn’t use any generics concept. The problem here is that the Finder class can only accept String-type list. But what if you want to pass other types of lists, such as Int or your own entity class? Maybe you can create another Finder class that receives other types of lists, but that method is not realistic and wastes so much of resources. Instead of that, why don’t we take advantage of Generics?

GenericsSample1.kt

fun main() {
    val myList = listOf("US", "UK", "AUS")
    val finder = Finder(list = myList)
    finder.findItem(element = "UK") {
        println("Found $it")
    }
}

class Finder(private val list: List<String>) {
    fun findItem(element : String, foundItem: (element : String?) -> Unit) {
        val itemFoundList = list.filter {
            it == element
        }
        if (itemFoundList.isNullOrEmpty()) foundItem(null) else
            foundItem(itemFoundList.first())
    }
}
$ java -jar GenericsSample1.jar
Found UK

Just like you can in the below code, <T> is Kotlin’s special type of Generics that is flexibly compatible with different types of data. Here, it corresponds to Car-class-type.

GenericsSample3.kt

fun main() {
    // val myList = listOf("US", "UK", "AUS")
    // val myNumList = listOf(255, 556, 778)
    val tesla1 = Car("white", "model3")
    val byd1 = Car("blue", "dolphin")
    val listOfcar = listOf(tesla1, byd1)
    val finder = Finder(list = listOfcar)
    finder.findItem(element = tesla1) {
        println("Found $it")
    }
}

class Car(var color : String, var model : String) {
    init {
        color = "Yellow"
        model = "Lexus"
    }
}

class Finder<T>(private val list: List<T>) {
    fun findItem(element : T, foundItem: (element : T?) -> Unit) {
        val itemFoundList = list.filter {
            it == element
        }
        if (itemFoundList.isNullOrEmpty()) foundItem(null) else
            foundItem(itemFoundList.first())
    }
}
$ java -jar GenericsSample3.jar
Found Car@7ba4f24f

Leave a Reply