Scala asInstanceOf with parameterized types

前端 未结 5 1224
清歌不尽
清歌不尽 2020-12-02 14:17

I would like to write a function that casts to type A, where A can be e.g. List[Int], or a more complicated parameterized type like Map[Int, List[Int]].

def          


        
5条回答
  •  忘掉有多难
    2020-12-02 15:01

    Yes, the problem occurs due to type erasure. If you try

    val x = List(1,2,3)
    val y = castToType[Int](x)
    

    The exception is thrown right away, as expected. The same occurs when trying to cast to Array[String] or even Array[Int].

    I don't think you can create a generic type converter that works will types inside collections and other objects. You will need to create a converter for each object type. For example:

    def castToType[A](x: List[A]) = x.map(i => i.asInstanceOf[A])
    

提交回复
热议问题