How can I invoke the constructor of a Scala abstract type?

后端 未结 3 773
攒了一身酷
攒了一身酷 2021-02-14 17:11

I\'m trying to figure out how to invoke a constructor for a Scala abstract type:

class Journey(val length: Int)
class PlaneJourney(length: Int) extends Journey(l         


        
3条回答
  •  眼角桃花
    2021-02-14 17:44

    Your class needs an implicit constructor parameter to get the Manifest. Then you can call erasure to get the Class and call newInstance, which reflectively calls the nullary constructor if there is one.

    class J[A](implicit m:Manifest[A]) {
      def n = m.erasure.newInstance()
    }
    
    new J[Object].n
    

    As of Scala 2.10, the erasure property in the manifest is deprecated. def n = m.runtimeClass.newInstance() does the same thing, but without warnings.

提交回复
热议问题