2017-08-08 8 views
1

私はいくつかの種類があります。暗黙の置換

trait OutputHandler[A] 

case class TypeA() 

case class TypeB() 

暗黙のパラメータを取る方法:

implicit val handler = new OutputHandler[TypeA] {} 

どのように私はジェネリックを作成することができますように定義

def process[A](a: Any => A)(implicit handler: OutputHandler[A]) {} 

値をList[T]の暗黙の値Tは、暗黙の値が定義されている任意の型にできますか?つまり、implicit val a: OutputHandler[TypeA]などがあるときはいつでもprocess(List(TypeA()))またはprocess(List(TypeB())に電話できますか?あなたはOutputHandler[List[A]]を返しimplicit defでこれを達成することができます

答えて

2

implicit val handler = new OutputHandler[TypeA] {} 

implicit def listOf[A](implicit ev: OutputHandler[A]): OutputHandler[List[A]] = new OutputHandler[List[A]] { 
    // can implement this output handler using ev: OutputHandler[A] 
} 

process(t => List(TypeA())) // compiles, because OutputHandler[TypeA] exists 
process(t => List(TypeB())) // does not compile, as expected, because there's no OutputHandler[TypeB] 
+0

ありがとうございました。うまくいく – ntviet18