Case Class Option 参数的不明确的隐式值 [英] Ambiguous Implicit Values for Case Class Option Parameter
问题描述
我正在做一些我在案例类和类型类上发明的练习.我遇到的问题之一如下:
I am going through some exercises I have invented on case classes and typeclasses. One of the problems I have faced is the following:
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()
}
case class Marker[T: Serializer](lst: Option[List[T]] = None)
Marker() // ambiguous implicit values: here...
}
现在这给出了关于不明确的隐含值的错误.我认为这与我之前问过的一个问题有关(尽管是不同的错误消息):
Now this gives an error about ambiguous implicit values. I think this is related to a question I have asked before (albeit a different error message):
我是否正确,即使错误消息不同,这里的工作过程也是相同的?
Am I correct in that it is the same process at work here, even though the error message is different?
推荐答案
编译器无法推断 T
.尝试明确指定 T
Compiler can't infer T
. Try to specify T
explicitly
Marker[String]() // compiles
Marker[Int]() // compiles
当您提供 lst
时,它可以推断 T
本身
When you provide lst
it can infer T
itself
Marker(Some(List(1, 2)))
Marker(Some(List("a", "b")))
出于同样的原因
Marker(Option.empty[List[Int]])
Marker(Option.empty[List[String]])
Marker[Int](None)
Marker[String](None)
Marker(None: Option[List[Int]])
Marker(None: Option[List[String]])
编译而 Marker(None)
不编译.
或者你可以优先考虑你的隐含
Alternatively you can prioritize your implicits
trait LowPrioritySerializer {
implicit object StringSerializer extends Serializer[String] {
def serialize(seq: List[String]): String = seq.toString()
}
}
object Serializer extends LowPrioritySerializer {
implicit object IntSerializer extends Serializer[Int] {
def serialize(seq: List[Int]): String = seq.toString()
}
}
然后 IntSerializer
将首先尝试,如果 IntSerializer
不起作用(如果类型不同),将第二次尝试 StringSerializer
.
Then IntSerializer
will be tried firstly and StringSerializer
will be tried secondly if IntSerializer
didn't work (if type is different).
这篇关于Case Class Option 参数的不明确的隐式值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!