Type match failed on map

I am learning Scala and trying to write simple code.

When I tried to write a method like this:

def func(value: Any) {
  value match {
    case i: Int => println(1)
    case vector: Vector[Any] => println(2)
    case map: Map[Any, Any] => println(3)
    case _ => println(4)
  }
}

I got a warning:

[warn]........:31: non-variable type argument Any in type pattern scala.collection.immutable.Map[Any,Any] (the underlying of Map[Any,Any]) is unchecked since it is eliminated by erasure
[warn]       case map: Map[Any, Any] => println(3)
[warn]                    ^
[warn] one warning found

I am wondering why use Map[Any, Any]will receive this warning, but Vector[Any]will not.

+4
source share
2 answers

The problem is that a is Map[X, Y]not covariant in its type parameter X(but a Vector[X]is).

What does it mean? Suppose B <: A(read, Bis a subtype A).

Vector[B] <: Vector[A]. : X Vector[B], B. , A . ( .)

, Map[X, B] <: Map[X, A] X ( , , ).

Map . , Map[B, X] <: Map[A, X] X.

:

val x: Map[B, X] = ???
x.get(b: B) // makes sense

val y: Map[A, X] = x // must be ok, Map[B, X] <: Map[A, X]
y.get(a: A) // bad! x doesn't know how to "get" with something of type `A`

, a Map[_, _] a Map[Any, Any]. , :

case map: Map[_, _] => ...
+3

, Map . , Map[Any,Any]. , Vector , Vector Vector[Any], , , Vector[Any] ( - ), Vector[String], Vector[Any].

+4

Source: https://habr.com/ru/post/1626154/


All Articles