Variance क्या है (Covariant/Contravariant)
In this page:
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 बिल्कुल अनुमति नहीं है।
उदाहरण: Variance (Covariant/Contravariant)
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)
}
Login to try C/C++/Java/PHP code in the editor
- किसी covariant type का mutable field declare करना, जैसे
class Box[+T](var item: T), जो compile नहीं होता। - यह मान लेना कि
Box[Dog]बिना+Tके एकBox[Animal]है, क्योंकि Scala classes default रूप से invariant होती हैं। +Tऔर-Tको मिला देना, जबकि covariance producers के लिए है और contravariance consumers के लिए।
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: