← Back to Scala Course | Chapter 12: Advanced Features | Lesson 3 of 7

Generics क्या हैं

Generics किसी class या function को placeholder का उपयोग करके कई types के साथ काम करने देते हैं, जैसे 'किसी भी चीज़ के लिए' लिखा एक box जिसे आप बाद में specify करते हैं। आप code एक बार लिखते हैं और किसी भी type के साथ उपयोग करते हैं।

In this page:

  1. Generics
Syntax
scala
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

markup
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)
}
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. #}
आम गलतियां
  1. class Box[T] लिखना और फिर new Box(1) और set("a"), जो fail होता है क्योंकि बनने के बाद T Int पर fixed हो जाता है।
  2. T का ऐसे उपयोग करना जैसे उसके methods हों, जैसे value.length, बिना T <: String जैसी bound के।
  3. type parameter के बजाय Any का उपयोग करना, जिससे type safety खो जाती है।
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.