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

后端 未结 3 753
攒了一身酷
攒了一身酷 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:29

    There is no direct way to invoke the constructor or access the companion object given only a type. One solution would be to use a type class that constructs a default instance of the given type.

    trait Default[A] { def default: A }
    
    class Journey(val length: Int)
    object Journey {
      // Provide the implicit in the companion
      implicit def default: Default[Journey] = new Default[Journey] {
        def default = new Journey(0)
      }
    }
    
    class Port[J <: Journey : Default] {
      // use the Default[J] instance to create the instance
      def startJourney: J = implicitly[Default[J]].default
    }
    

    You will need to add an implicit Default definition to all companion objects of classes that support creation of a default instance.

提交回复
热议问题