List of classes implementing a certain typeclass

后端 未结 4 961
陌清茗
陌清茗 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条回答
  •  旧时难觅i
    2021-02-15 11:39

    Disclamer: I've made this answer to provide a solution to the concrete development problem, and not the theoretical problem of using typeclass


    I would do it this way:

    trait Showable{ def show(): String }
    
    implicit class IntCanShow(int: Int) extends Showable {
      def show(): String = s"int $int"
    }
    
    implicit class StringCanShow(str: String) extends Showable {
      def show(): String = str
    }
    
    val l: List[Showable] = List(1,"asd")
    

    Note that I changed the meaning of the trait Show, into Showable, such that the implementing classes are used as wrapper. We can thus simply require that we want Showable instances (and because those classes are implicit, input of the List are automatically wrapped)

提交回复
热议问题