簡體   English   中英

Scala從泛型類型實例化具體類

[英]Scala instantiate a Concrete Class From Generic Type

我有一個通用的特性,如下所示:

trait MyTrait[T] {
  def doSomething(elems: Seq[T])
}

然后我有一個對象工廠,其定義如下:

object MyTraitFactory {
  def apply[T](param1: Boolean, param2: Boolean): MyTrait[T] = {
    // based on the type of T, I would like to instantiate sub types
  }
}

我已經得到了具體的實現,例如:

class MyStringTrait extends MyTrait[String]

class MyIntTrait extends MyTrait[Int]

我現在需要那個在我的對象工廠中尋找類型的魔術位並實例化相應的實現。 有什么建議?

這可以使用隱式類型類在scala中解決。 為每種類型創建具有具體實現的工廠特征:

object MyTraitFactory {

  def apply[T](param1: Boolean, param2: Boolean)(implicit factory: MyTraitCreator[T]): MyTrait[T] = {
    // call the typeclass create method
    factory.create(param1, param2)
  }

  // factory trait
  trait MyTraitCreator[T] {
    def create(param1: Boolean, param2: Boolean): MyTrait[T]
  }

  // provide an implicit factory object for the specific types:
  object MyTraitCreator {

    implicit object MyStringTraitCreator extends MyTraitCreator[String] {
      override def create(param1: Boolean, param2: Boolean): MyTrait[String] = {
        // create the String type here
        new MyStringTrait
      }
    }

    implicit object MyIntTraitCreator extends MyTraitCreator[Int] {
      override def create(param1: Boolean, param2: Boolean): MyTrait[Int] = {
        // create the Int type here
        new MyIntTrait
      }
    }
  }
}

Scala使用隱式參數“隱藏”類型類。 但為了使其工作,您必須確保將隱式工廠對象保留在編譯器查找隱含的位置(例如,如上所述的MyTraitCreator的伴隨對象)。 該模式也可以在沒有implicit情況下工作,但隨后需要調用者在每次調用時提供具體工廠。

該解決方案包含大量鍋爐板代碼,但在編譯時靜態工作,不會遭受類型擦除。 它甚至還帶有scala中的語法糖:

def apply[T: MyTraitCreator](param1: Boolean, param2: Boolean): MyTrait[T] = {
    // call the typeclass create method
    implicitly[MyTraitCreator[T]].factory.create(param1, param2)
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM