Reputation: 473
I tried various solutions but was not able to figure out the correct solution
val list: List[Any] = List(1,2,List(1,2))
The output should be -> 2
Upvotes: 0
Views: 255
Reputation: 86
I can think of a couple of ways to do this, but, as stated above, more accurate typing would be better.
list match {
case _ :: _ :: (_ :: elem :: Nil) :: Nil => Some(elem)
case _ => None
}
Of course this pattern is tailored to your exact use case 'list' and would fail to find your number in a lot of cases. Say to find the first List element in your 'list' and get it's second element I'd do
list.collectFirst {
case _ :: elem :: _ => elem
}
But again, this may not support all your needs in general. To find the nth List element's mth element in your 'list', you could
list.collect {
case l: List[_] => l // compiler warning maybe?
}.lift(n).flatMap(_.lift(m))
Upvotes: 0
Reputation: 51271
The correct solution is to avoid mixing types in a List
. If you have type Any
then you're in a corner. The compiler doesn't know what type the elements are so it won't let you do anything meaningful with them.
The only way out of the posted problem is to cast the elements to the required type, which is very bad Scala style. It's also dangerous. If you cast incorrectly the program blows up.
scala> list.last.asInstanceOf[List[Int]](1)
res0: Int = 2
If you have to tell the compiler what the element type is then you're not using the compiler and/or the language to its full potential.
Upvotes: 1