I have an input List
var list=List(List(1, 1), 2, List(3, List(5, 8)))
and i need it to be flattened as "List(1, 1, 2, 3, 5, 8)".
since my input list contains List[Int],Int,List[Any],i cannot flatten it using the flatten function.so i wrote my own flat function.
object HelloWorld {
def main(args: Array[String]) {
println(flat(List(List(1, 1), 2, List(3, List(5, 8)))))
//println(flat(List(List(1, 1), 2, List(3, 4))))
}
def flat(lst:List[Any]):List[Any]={
lst.flatMap{
case a:List[Int] => a
case b:Int => List(b)
case c:List[Any] => flat(c)
}
}
}
I am leaving the input as it is if it is List[Int],for an integer i am converting it into a List and for a List[Any], i am recursively calling my own flat function.
The code executes but i am not getting my desired output.Apart from that,i receive two warnings.
o/p :List(1, 1, 2, 3, List(5, 8))
jdoodle.scala:5: warning: non-variable type argument Int in type pattern List[Int] (the underlying of List[Int]) is unchecked since it is eliminated by erasure case a:List[Int] => a ^
jdoodle.scala:7: warning: unreachable code case c:List[Any] => flat(c) ^ warning: there was one deprecation warning (since 2.13.0); re-run with -deprecation for details
Any idea where i am going wrong.Much appreciated.
Note:I am able to get the desired o/p using the below code
object HelloWorld {
def main(args: Array[String]) {
println(flat(List(List(1, 1), 2, List(3, List(5, 8)))))
}
def flat(list: List[Any]): List[Any] = { list.flatMap{
case i: List[Any] => flat(i)
case e => List(e)
}
}
}
I just need to know why the 1st approach at the beginning wouldnt work.