List of classes implementing a certain typeclass

后端 未结 4 1555
深忆病人
深忆病人 2021-02-15 10:47

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:26

    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)

提交回复
热议问题