Reputation: 13
scala >
var a : Any = List(1,2,3,4,5,6,7,8,9,0)
I want to iterate variable a. as it print
1
2
3
4
5
6
7
8
9
0
Upvotes: 1
Views: 150
Reputation: 48410
Collections such as List
are usually "iterated" over using map/foreach
higher-order methods, however the reason we cannot call them directly on a
is because compiler thinks the type of a
is Any
as we explicitly specified type annotation a: Any
.
var a: Any = List(1,2,3,4,5,6,7,8,9,0)
| |
compile-time type runtime class
Any
does not provide map/foreach
API so the best we can do is it to perform a runtime cast of reference a
to class List[_]
like so
if (a.isInstanceOf[List[_]]) a.asInstanceOf[List[_]].foreach(println) else ???
which can be equivalently sugared using pattern match
a match {
case value: List[_] => value.foreach(println)
case _ => ???
}
As a side-note, due to type erasure we can only check the "top-level" class List
and not, for example, List[Int]
, hence a.isInstanceOf[List[Int]]
is a bit misleading so I prefer expressing it a.isInstanceOf[List[_]]
.
Upvotes: 2
Reputation: 26046
Just use pattern matching:
a match {
case l: List[Int] => l.foreach(println)
}
P.S.: As @IvanStanislavciuc cleverly notices, there is a warning:
warning: non-variable type argument Int in type pattern List[Int] (the underlying of List[Int]) is unchecked since it is eliminated by erasure 1
It's because of type erasure, but List
needs a type parameter, so you can as well pass Any
instead of Int
.
Upvotes: 2