The issue is List
is defined as List[+A]
(source). Which means List
takes a type parameter of co-variant type. (You can think of co-variance as type converting from narrow to broader. For ex: if Dog
extends Animal
and if you do Animal a = new Dog()
, you have a Dog (narrow) converting to Animal (broader))
x
is of type List[Object]
. Doing
scala> val x = List ("item1" , "item2" , List ("a,b,c"))
x: List[Object] = List(item1, item2, List(a,b,c))
val list_from_x :List [String]= x(2)
is ultimately converting from List[Object]
(broader) to List[String]
(narrow). Which is contra-variant. Hence the compiler threw error because List is meant to be co-variant.
For ex: the below is completely valid. Thanks to co-variance:
scala> val x = List("hello")
x: List[String] = List(sdf)
scala> val o:List[Object] = x
o: List[Object] = List(sdf)
More about it here and here