dimanche 5 juillet 2020

How to Prioritise Implicits for More than 2 cases

I was recently introduced to the technique of prioritising implicits here:Link

Now, I am trying to generalise this to cases where the number of implicits > 2.

From this answer here, it says I can do this by creating a hierarchy of traits: Link

Here is some code where I would like to prioritise implicits:

object Example extends App {

  sealed trait Serializer[T] {
    def serialize(seq: List[T]): String
  }

  implicit object StringSerializer extends Serializer[String] {
    def serialize(seq: List[String]): String = seq.toString()
  }

  implicit object IntSerializer extends Serializer[Int] {
    def serialize(seq: List[Int]): String = seq.toString()
  }

  implicit object FloatSerializer extends Serializer[Float] {
    def serialize(seq: List[Float]): String = seq.toString()
  }

  case class Marker[T: Serializer](lst: Option[List[T]] = None)
  
  Marker() // ambiguous implicit values: here...
}

How could I impose the implicit priority of Float > Int > String in this case?

My attempt was as follows:

trait A {
    implicit object StringSerializer extends Serializer[String] {
      def serialize(seq: List[String]): String = seq.toString
    }
  }
  
  trait B extends A {
    implicit object IntSerializer extends Serializer[Int] {
      def serialize(seq: List[Int]): String = seq.toString
    }
  }

  trait C extends B {
    implicit object FloatSerializer extends Serializer[Float] {
      def serialize(seq: List[Float]): String = seq.toString
    }
  }

But this didn't work. Looking at the code I can see I am not doing it properly but I am unsure how to proceed.

Any guidance would be much appreciated.

Aucun commentaire:

Enregistrer un commentaire