AnyCompiler

Generics

Box<T> ek generic class hai — T ek placeholder hai jo jahan bhi Box istemal ho wahan ek real type se fill ho jata hai. Box("hello") argument se khud ba khud Box<String> infer karta hai, aur compiler har istemal par type safety check karta hai.

class Box<T>(private val contents: T) {
    fun getValue(): T = contents
}

fun main() {
    val box = Box("hello")
    println(box.getValue())
}
Output
hello

Aage: exceptions, aur is course ne kya cover kiya us ka ek closing look.

Practice exercise

Ek generic class Box<T> define karein jis ki private contents property ho aur ek getValue() method ho. "hello" rakhne wala ek Box banayein, phir us ka value print karein.