Generics क्या हैं
Generics किसी class या function को placeholder का उपयोग करके कई types के साथ काम करने देते हैं, जैसे 'किसी भी चीज़ के लिए' लिखा एक box जिसे आप बाद में specify करते हैं। आप code एक बार लिखते हैं और किसी भी type के साथ उपयोग करते हैं।
In this page:
Syntax
class Box[T](value: T) {
def get: T = value
}
def function_name[T](param: T): T = param
val box = new Box[Type](value)
Generics
एक generic class या function एक type parameter का उपयोग करता है, जैसे class Box[T], ताकि वही definition किसी भी type के साथ काम करे जबकि पूरी तरह type-safe रहे।
concrete type तब दिया जाता है (या infer होता है) जब class instantiate होती है या function call होता है, जैसे Box[Int] या Box[String]। यह आपको चाहिए हर type के लिए एक जैसा logic दोहराने से बचाता है।
Note:
Generic type parameters को convention के अनुसार T, A, या key-value pairs के लिए K/V जैसे single uppercase letters नाम दिए जाते हैं।
उदाहरण: Generics
class Box[T](private var value: T) {
def get: T = value
def set(newValue: T): Unit = { value = newValue }
}
object Main extends App {
val intBox = new Box[Int](42)
val strBox = new Box[String]("hello")
println(intBox.get)
println(strBox.get)
}
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
आम गलतियां
class Box[T]लिखना और फिरnew Box(1)औरset("a"), जो fail होता है क्योंकि बनने के बादTIntपर fixed हो जाता है।Tका ऐसे उपयोग करना जैसे उसके methods हों, जैसेvalue.length, बिनाT <: Stringजैसी bound के।- type parameter के बजाय
Anyका उपयोग करना, जिससे type safety खो जाती है।
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: