Question

How to check which instance is the current object. Specifically check if its a Collection.

val maps = Map("s" -> 2, "zz" -> 23, "Hello" -> "World", "4" -> Map(11 -> "World"), "23333" -> true);

for(element <- maps) {
    if(element.isInstanceOf[Map]) { // error here
         print("this is a collection instance ");
    } 
    println(element);
}
Était-ce utile?

La solution

If you want to detect any Map:

for(element <- maps) {
    if(element.isInstanceOf[Map[_, _]]) {
         print("this is a collection instance ")
    } 
    println(element)
}

But this didn't work because you check whole tuple ("s" -> 2 etc.) instead of second element of tuple:

for(element <- maps) {
    if(element._2.isInstanceOf[Map[_, _]]) {
         print("this is a collection instance ")
    }
    println(element._2)
}

Or with pattern matching:

for((_, v) <- maps) {
    if(v.isInstanceOf[Map[_, _]]) {
         print("this is a collection instance ")
    }
    println(v)
}

Or with even more pattern matching:

maps foreach {
    case (_, v: Map[_, _]) => println("this is a collection instance " + v)
    case (_, v)            => println(v)
}

Autres conseils

To be able to compile your snippet, change it to

if (element.isInstanceOf[Map[_, _]]) {

but as you are iterating over "key/value pairs", it will never match.


So probably you wanted something like this: To iterate over the values:

maps.values.foreach {
  case (m: Map[_, _]) => println(s"Map: $m" )
  case x => println(x)
}

or if you want to iterate over the key/value pairs:

maps foreach {
  case (key, m: Map[_, _]) => println(s"Map: $key -> $m" )
  case (key, value) => println(s"$key -> $value")
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top