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

Variance क्या है (Covariant/Contravariant)

Variance बताता है कि क्या एक type का box किसी संबंधित type के box की जगह ले सकता है, जैसे cats की एक basket animals की basket गिनी जाए। Scala यह बताने के लिए plus और minus signs उपयोग करता है।
Syntax
scala
class Box[+T](value: T)    // covariant
trait Handler[-T]          // contravariant

Variance (Covariant/Contravariant)

Covariance, class Box[+T] से declared, Box[Dog] को वहां उपयोग करने देता है जहां Box[Animal] की उम्मीद हो, type parameter के subtype संबंध को बनाए रखते हुए।

Contravariance, class Printer[-T] से declared, विपरीत दिशा में काम करता है -- एक Printer[Animal] को वहां उपयोग किया जा सकता है जहां Printer[Dog] की उम्मीद हो, क्योंकि यह वह सब कुछ handle कर सकता है जो कोई Animal-या-ज़्यादा-general printer कर सकता है। Default रूप से (कोई +/- नहीं), एक type parameter invariant होता है, जिसका मतलब है कि ऐसा कोई substitution बिल्कुल अनुमति नहीं है।

Note: Covariant (+T) type parameters आमतौर पर सिर्फ output/return positions तक सीमित होते हैं -- इन्हें किसी method parameter type के रूप में उपयोग करना आमतौर पर एक compile error देता है।

उदाहरण: Variance (Covariant/Contravariant)

markup
class Animal(val name: String)
class Dog(name: String) extends Animal(name)

class Box[+T](val item: T)

object Main extends App {
  val dogBox: Box[Dog] = new Box(new Dog("Rex"))
  val animalBox: Box[Animal] = dogBox // allowed because Box is covariant

  println(animalBox.item.name)
}
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. किसी covariant type का mutable field declare करना, जैसे class Box[+T](var item: T), जो compile नहीं होता।
  2. यह मान लेना कि Box[Dog] बिना +T के एक Box[Animal] है, क्योंकि Scala classes default रूप से invariant होती हैं।
  3. +T और -T को मिला देना, जबकि covariance producers के लिए है और contravariance consumers के लिए।
🔒

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.