How do I create an instance of a trait in a generic method in scala?

前端 未结 2 1176
暗喜
暗喜 2020-12-05 21:25

I\'m trying to create an instance of a trait using this method

val inst = new Object with MyTrait

This works well, but I\'d like to move th

2条回答
  •  [愿得一人]
    2020-12-05 22:04

    I'm not sure what the motivation is for your question, but you could consider passing a factory for T as an implicit parameter. This is known as using type classes or ad-hoc polymorphism.

    object Test extends Application {
      trait Factory[T] {
        def apply: T
      }
      object Factory {
        /**
         * Construct a factory for type `T` that creates a new instance by
         * invoking the by-name parameter `t`
         */
        def apply[T](t: => T): Factory[T] = new Factory[T] {
          def apply = t
        }
      }
    
      // define a few traits...
      trait T1
      trait T2
    
      // ...and corresponding instances of the `Factory` type class.
      implicit val T1Factory: Factory[T1] = Factory(new T1{})
      implicit val T2Factory: Factory[T2] = Factory(new T2{})
    
      // Use a context bound to restrict type parameter T
      // by requiring an implicit parameter of type `Factory[T]`
      def create[T: Factory]: T = implicitly[Factory[T]].apply
    
      create[T1]
      create[T2]
    
    }
    

    At the other end of the spectrum, you could invoke the compiler at runtime, as detailed in this answer to the question "Dynamic mixin in Scala - is it possible?".

提交回复
热议问题