【问题标题】:Why does my type check on nested collection fails in this case?为什么在这种情况下我对嵌套集合的类型检查会失败?
【发布时间】:2013-07-29 10:56:02
【问题描述】:

如何检查哪个实例是当前对象。具体检查它是否是一个集合。

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);
}

【问题讨论】:

  • 您遇到的错误是什么?当它“失败”时会发生什么?
  • @AndrzejDoyle 我猜 Ryan 的意思是它只是绕过检查而不是进入 if 语句
  • @om-nom-nom:编译错误:error: type Map takes type parameters.

标签: scala collections instanceof


【解决方案1】:

如果你想检测任何Map:

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

但这不起作用,因为您检查的是整个元组(“s”-> 2 等)而不是元组的第二个元素:

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

或者使用模式匹配:

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

或者更多的模式匹配:

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

【讨论】:

    【解决方案2】:

    为了能够编译您的 sn-p,请将其更改为

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

    但是当您迭代“键/值对”时,它永远不会匹配。


    所以你可能想要这样的东西:迭代值:

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

    或者如果您想遍历键/值对:

    maps foreach {
      case (key, m: Map[_, _]) => println(s"Map: $key -> $m" )
      case (key, value) => println(s"$key -> $value")
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-17
      • 1970-01-01
      • 2023-03-16
      • 2014-05-31
      相关资源
      最近更新 更多