Last active
November 4, 2020 01:30
-
-
Save rupeshtr78/9f0a791dbbf005b5afabcb5e902af663 to your computer and use it in GitHub Desktop.
variance
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Big rule → Functions | |
//“Be liberal in what you accept from others” | |
//“Be conservative in what you do” | |
//type Function[-A, +B] = Function1[A, B] | |
//the inputs of functions are contravariant and output are covariant. | |
//method arguments are in CONTRAVARIANT position -A (more general input argument) | |
//return types are in COVARIANT position +B (more specific return type) | |
//In most cases, | |
//A will be the type parameter of the class | |
//B will be the type parameter of a method. | |
//Errors | |
//Covariant Class | |
//Covariant type A occurs in contravariant position in type A of value C | |
//ContraVariant Class | |
//Contravariant type A occurs in covariant position in type A of value C | |
//Covariant Class | |
//Convert input to Contravariant using lower type bounds >: | |
//Make input the SuperType ( make general) | |
//Widen the Type | |
class Sounds3[+A]{ | |
def sound[C >:A](animal:C) = animal | |
} | |
val a3:Sounds3[Cat] = new Sounds3[Tiger] | |
//ContraVariant Class | |
//Convert output Covariant using Upper Type Bounds <: | |
//Make input SubType ( make specific) | |
//Narrowing the Type | |
class Sounds4[-A]{ | |
def sound[C <:A](animal:C) = animal | |
} | |
val a4:Sounds4[Tiger] = new Sounds4[Cat] | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment