List of classes implementing a certain typeclass

后端 未结 4 939
陌清茗
陌清茗 2021-02-15 11:02

I would like to define a List of elements implementing a common type class. E.g.

  trait Show[A] {
    def show(a: A): String
  }
  implicit val int         


        
4条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-02-15 11:35

    An alternative way of handling this would be to use the shapeless library. I would really reccommend this book which explains shapeless in a clear and concise manner.

    Shapeless provides two things that I think will help you in this case:

    1. Heterogeneous lists (HList)
    2. Polymorphic functions to enable the HList mapping operation.

    First import the required libraries (shapeless):

    import shapeless.{HNil, Poly1, ::}
    

    Create a heterogeneous list of whatever types you require. Note the type annotation is only there for clarity.

    val data : Int :: String :: HNil = 1 :: "hello" :: HNil
    

    Create a polymorphic function defining an implicit value for every type you require.

    object Show extends Poly1 {
        implicit def atT[T: Show] = at[T] (implicitly[Show[T]].show)
    }
    

    Shapeless provides an extension method for map on a HList to enable applying the show function to every element in the list

    val result : String :: String :: HNil = data.map(Show)
    

    Edited: thanks to @dk14 for the suggested improvement to the definition of the Show polymorphic function.

提交回复
热议问题