AnyCompiler

Generics

Box<T> ek generic class hai — T ek placeholder hai jo jahan bhi Box use ho wahan ek real type se fill ho jata hai. Box("hello") argument se automatically Box<String> infer karta hai, aur compiler har use 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 uska ek closing look.

Practice exercise

Ek generic class Box<T> define karo jiski private contents property ho aur ek getValue() method ho. "hello" rakhne wala ek Box banao, phir uska value print karo.