Scala: reconciling type classes with dependency injection

前端 未结 3 1440
野的像风
野的像风 2021-01-31 20:06

There seems to be a lot of enthusiasm among Scala bloggers lately for the type classes pattern, in which a simple class has functionality added to it by an addi

3条回答
  •  情歌与酒
    2021-01-31 20:45

    A fair amount of the tediousness of passing down those implicit dependencies can be alleviated by using the new context bound syntax. Your example becomes

    def writeAll[T:Foo] (items: List[T]) =
      items.foreach(w => implicitly[Foo[T]].write(w))
    

    which compiles identically but makes for nice and clear signatures and has fewer "noise" variables floating around.

    Not a great answer, but the alternatives probably involve reflection, and I don't know of any library that will just make this automatically work.

提交回复
热议问题