1. Generic Functions and Classes

[THEORY]

[PREDICT]

Read the code carefully before you run it.

prediction.kt
class StorageBin<T>(val content: T)

fun main() {
    val bin1 = StorageBin(42)
    val bin2 = StorageBin("Network cable")
    println(bin1.content)
    println(bin2.content)
}

What does this program print? Do you have to state the type `T` explicitly anywhere when calling `StorageBin(...)` for it to compile?

[TASK]

Write a generic function lastElement that returns the last element of a list of any type — or null if the list is empty. The function should work for every list without constraining T, whether List<String>, List<Int> or a list of your own classes.

task.kt
fun main() { val referenceNumbers = listOf("A-100", "A-101", "A-102") val quantities = listOf(5, 12, 3) val empty = emptyList<String>() // TODO: Call lastElement with all three lists and print the results. } // TODO: Write the generic function lastElement<T>(list: List<T>): T?

Before you get a hint: what have you tried, and where exactly are you stuck?

[COMPREHENSION CHECK]

1. What does the type parameter T stand for in class StorageBin<T>(val content: T)?

2. Without generics you would have to write a separate class for StorageBin<Int>, StorageBin<String> and StorageBin<Order>. What is the main reason to avoid that with generics?

3. Do you have to write the type T explicitly as StorageBin<Int>(42) for val box = StorageBin(42)?