简体   繁体   English

如何为超过 2 个案例优先考虑隐式

[英]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.现在,我试图将其推广到隐含数 > 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?在这种情况下,我如何强加 Float > Int > String 的隐式优先级?

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.任何指导将不胜感激。

For example you can do例如你可以做

val c = new C {}
import c._

Marker() //compiles

or或者

object c extends C
import c._

Marker() //compiles

Or make C an object rather than trait或者使C成为 object 而不是 trait

object C extends B {
  implicit object FloatSerializer extends Serializer[Float] {
    def serialize(seq: List[Float]): Value = ???
  }
}

import C._

Marker() //compiles

If you make C an object and rename it to Serializer (so C became the companion object of trait Serializer ) then you'll not have to make the import If you make C an object and rename it to Serializer (so C became the companion object of trait Serializer ) then you'll not have to make the import

object Serializer extends B {
  implicit object FloatSerializer extends Serializer[Float] {
    def serialize(seq: List[Float]): Value = ???
  }
}

Marker() //compiles

Where does Scala look for implicits? Scala 在哪里寻找隐式?

Where does Scala look for implicits? Scala 在哪里寻找隐式?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM