Erasure elimination in scala : non-variable type argument is unchecked since it is eliminated by erasure

前端 未结 2 988
予麋鹿
予麋鹿 2020-12-23 15:04

I\'ve got a sequence Seq[Any] that has a variety of objects in it (like String, Integer, List[String], etc). I\'m trying to sift through the list and break it up into separa

2条回答
  •  Happy的楠姐
    2020-12-23 15:23

    val v = 1 ::"abc" :: true :: Nil
    v : List[Any] = List(1,abc,true) 
    

    type parameter of List type has been unified to the greatest common super type of the elements in the List which is Any.

    Shapeless is to the rescue.

    import shapeless._
    import HList._
    
    val s = 1 :: "abc" :: true: HNil
    s : shapeless.::[Int,shapeless.::[String,shapelsss.::[Boolean,shapeless.HNil]]]
    = 1 :: abc :: true :: HNil
    

    With Shapeless HList you can get compile time safety for a heterogeneous list. you can now filter in a typesafe manner. e.g.

    s.filter[String]
    

提交回复
热议问题