user3103957
user3103957

Reputation: 848

Covariance in method parameters in Scala

In covariance, methods are not allowed to have parameters if the type of the parameters are same as Generic type. This is due to fact that then it becomes feasible to pass super class objects of the type parameter. That is:

class Parent
class Child extends Parent

class Generic[+T] {
   def func(t:T) = ???
}

val x :Generic[Chiild] = new Generic[Child]
val y :Generic[Parent] = x
y.func(new Child)          //This one is illegal; Hence methods are not allowed to have parameters where their type is T.

This is very intuitive & easy to reason. Same thing is said for contravariant where return type is not allowed.

But if we want to make the method in covariance to accept parameters, it can be done in the below manner as per many blogs/articles. I have given the complete example below.

Intuitively, it makes sense if E in the 'func', is sub type of T. Here, if it is Apple or PinkLady, then it makes sense. Because X is initialized with Apple. Due to the same reason, marking covariant type in method parameters is prohibited in my first point (i.e: Fruit is not allowed to be passed).

But here, everything is accepted Ideally when Fruit is passed, it should throw error. I am really confused why Fruit object is accepted. Hence, E must be upper bound (but it is errored out by compiler).

    class Fruit
    class Apple extends Fruit
    class PinkLady extends Apple

class Generic[+T] {
   def func[E >: T](e:E) = "Hello"     //Function definition        
}

val x = new Generic[Apple]

x.func(new Fruit)
x.func(new Apple)
x.func(new PinkLady)

Can some one please help me to understand.

Thanks in advance.

Upvotes: 0

Views: 145

Answers (1)

amorfis
amorfis

Reputation: 15770

Covariance of T is not important here - it works the same without it (Generic[T]). It's because when passing the parameters to function, the only condition is that it has to be supertype of T - so Any works too. And everything is Any, so you can pass Apple, "your name", or anything else.

Upvotes: 3

Related Questions