Reputation: 181
val wordList = List("I", "want", "to", "learn", "scala")
val wordSizeList = list.map(x=>x.length)
def func[A, B](a:List[A]):List[B]={
a.collect({case x:B => x})
}
val result = func[Any, Int](wordList ::: wordSizeList)
Below is the worksheet result
wordList: List[String] = List(I, want, to, learn, scala)
wordSizeList: List[Int] = List(1, 4, 2, 5, 5)
func: [A, B](a: List[A])List[B]
result: List[Int] = List(I, want, to, learn, scala, 1, 4, 2, 5, 5)
why doesn't it filter based on the Generic type "B"? And if you see the result list, how can a Int type list can contain String as well?
Upvotes: 2
Views: 73
Reputation: 22449
Looks to me a type erasure problem, which can be remedied with a ClassTag
:
import scala.reflect.ClassTag
def func[A, B : ClassTag](a: List[A]): List[B] = {
a.collect{ case x: B => x }
}
val result = func[Any, Int](wordList ::: wordSizeList)
// result: List[Int] = List(1, 4, 2, 5, 5)
Upvotes: 6