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
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)