[Scala] Generics tip du jour
Author |
Message |
wtd
|
Posted: Tue Oct 16, 2007 1:38 am Post subject: [Scala] Generics tip du jour |
|
|
So you create a generic class Foo.
Now, you have classes A and B.
code: | class A
class B extends A |
Now, we can do something very simple.
code: | val bar: Foo[A] = new Foo[A]
val baz: Foo[B] = new Foo[B] |
It works fine. Now, let's extend Foo.
code: | class Foo[T]
class Bar[T] extends Foo[T] |
And now the following works fine too.
code: | val bar: Foo[A] = new Bar[A]
val baz: Foo[B] = new Bar[B] |
But... what about...
code: | val bar: Foo[A] = new Foo[B] |
This fails!
But, why should it? B is a subtype of A, so Foo[B] should be a subtype of Foo[A], right?
We can make it work.
code: | class Foo[+T]
class Bar[+T] extends Foo[T] |
Now we can even...
code: | val baz: Foo[A] = Bar[B] |
|
|
|
|
|
|
Sponsor Sponsor
|
|
|
|
|