2013-07-29 47 views
0

如何檢查當前對象是哪個實例。具體檢查一下它的收藏。爲什麼我的類型檢查嵌套收集在這種情況下失敗?

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

什麼你得到的錯誤?當它「失敗」時會發生什麼? –

+0

@AndrzejDoyle我猜Ryan意味着它只是繞過檢查而不是步入if語句 –

+0

@ om-nom-nom:編譯錯誤:'錯誤:輸入Map類型參數'。 – senia

回答

0

如果你想檢測到任何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) 
} 
+0

謝謝..這是我想要的。 – Ryan

0

爲了能夠編譯代碼片段,將其更改爲

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") 
} 
相關問題