[scala] Why isn't immutable Map contravariant in its key type?

Previous Topic Next Topic
 
classic Classic list List threaded Threaded
4 messages Options
Reply | Threaded
Open this post in threaded view
|

[scala] Why isn't immutable Map contravariant in its key type?

Paul Chiusano
If I have a Map[Any,V], it seems like I should be able to use that anywhere I need say, a Map[Int,V], just like I can use a Function1[Any,V] at any site needing Function1[Int,V]. Is there some reason why Map can't be contravariant in its key type? Is the restriction artificial?

Paul
Reply | Threaded
Open this post in threaded view
|

Re: [scala] Why isn't immutable Map contravariant in its key type?

Martin Odersky
Map returns elements of the Key type in its keys iterator. That's a
covariant occurrence, so Map can't be contravariant in Key.

Cheers

 -- Martin

On Mon, Sep 15, 2008 at 5:36 PM, Paul Chiusano <[hidden email]> wrote:
> If I have a Map[Any,V], it seems like I should be able to use that anywhere
> I need say, a Map[Int,V], just like I can use a Function1[Any,V] at any site
> needing Function1[Int,V]. Is there some reason why Map can't be
> contravariant in its key type? Is the restriction artificial?
>
> Paul
>
Reply | Threaded
Open this post in threaded view
|

Re: [scala] Why isn't immutable Map contravariant in its key type?

David MacIver
On Mon, Sep 15, 2008 at 11:41 AM, martin odersky <[hidden email]> wrote:
> Map returns elements of the Key type in its keys iterator. That's a
> covariant occurrence, so Map can't be contravariant in Key.

Also, practically speaking, it's impossible to implement for many
interesting types of map.

In particular any ordered map implementation can't be made to work
properly with a contravariant key type.
Reply | Threaded
Open this post in threaded view
|

Re: [scala] Why isn't immutable Map contravariant in its key type?

Paul Chiusano
This makes sense, thank you both.

Also, I realized that since Map[Any,V] extends Function1[Any,V], you can still pass such a Map[Any,V] as a Function1[K,V] for any K. Or in general, a class, C which extends a trait, T, will still preserve the variances of T when C is being used as an instance of T.

On Mon, Sep 15, 2008 at 1:38 PM, David MacIver <[hidden email]> wrote:
On Mon, Sep 15, 2008 at 11:41 AM, martin odersky <[hidden email]> wrote:
> Map returns elements of the Key type in its keys iterator. That's a
> covariant occurrence, so Map can't be contravariant in Key.

Also, practically speaking, it's impossible to implement for many
interesting types of map.

In particular any ordered map implementation can't be made to work
properly with a contravariant key type.