Variance

A good example, the book "Programming Scala" by Dean Wampler & Alex Payne. 
Page 283


trait Function2[-T1, -T2, +R] extends AnyRef


The last type parameter, +R, the is the return type. It is covariant. The leading two type
parameters are for the first and second function arguments, respectively. They are
contravariant.
 

class CSuper { def msuper() = println("CSuper") }
class C extends CSuper { def m() = println("C") }
class CSub extends C { def msub() = println("CSub") }

var f: C => C = (c: C) => new C //
f = (c: CSuper) => new CSub // c: CSuper is valid, because the argument
                            // C is contravariant, so CSuper is a valid substitution
                            // while the return value is covariant, so CSub is a valid replacement for C.
f = (c: CSuper) => new C    // Similar to the previous case, but we simply return a C.
f = (c: C) => new CSub      // Similar to the previous cases, but we simply pass a C.
f = (c: CSub) => new CSuper // An error! A function that takes a CSub argument is invalid, because of
                            // contravariance, and the return type CSuper is invalid due to covariance.

Комментарии

Популярные сообщения из этого блога

Loading data into Spark from Oracle RDBMS, CSV

Load data from Cassandra to HDFS parquet files and select with Hive

Hadoop 3.0 cluster - installation, configuration, tests on Cent OS 7