【发布时间】:2017-01-26 08:30:18
【问题描述】:
我遇到了一个与此多参数类型类实现相关的奇怪错误
trait Feedtype
trait Atom extends Feedtype
trait Rss2 extends Feedtype
case object Atom extends Atom
case object Rss2 extends Rss2
trait Encoding
trait Xml extends Encoding
trait Json
case object Json extends Json
case object Xml extends Xml
trait Content
case class show[T <: Feedtype,E <: Encoding](str: String, tp: T, en: E) extends Content
trait TypeClass[C,D,E] {
def show(c: C, d: D, e:E): String
}
trait Service{
def print[T,C,D](t: T,c:C, d:D)(implicit s: TypeClass[T,C,D]): String
}
object Service extends Service{
def print[T,C,D](t:T, c:C, d:D)(implicit s: TypeClass[T,C,D]): String =
s.show(t,c,d)
}
implicit val t1 = new TypeClass[show[Atom,Xml], Atom, Xml] {
def show(c: show[Atom,Xml], d:Atom, e:Xml) = c.str
}
implicit val t2 = new TypeClass[show[Rss2,Xml], Rss2, Xml] {
def show(c: show[Rss2,Xml], d:Rss2, e:Xml) = "hi there " + c.str
}
val s1 = show("some show", Atom, new Xml {})
Service.print(s1, s1.tp, s1.en)
我得到的错误是
type mismatch;
found : A$A10.this.typeclass[A$A10.this.show[A$A10.this.atom,A$A10.this.xml],A$A10.this.atom,A$A10.this.xml]
required: A$A10.this.typeclass[A$A10.this.show[A$A10.this.atom.type,A$A10.this.xml.type],A$A10.this.atom.type,A$A10.this.xml.type]
service.print(s1, s1.tp, s1.en)(t1);}
^
我在这里错过了什么?
更新
我发现问题在于atom 和xml 在被用作创建s1 的值时是case objects。如果我使用new atom {} 或new xml {},那么执行会正常进行。但是,我想知道为什么 case objects 被认为与它们所代表的类型不同?
【问题讨论】:
-
什么是
atom?请发布minimal reproducible example您的问题。 -
遗漏了部分代码,现已修复。道歉和感谢
标签: scala types functional-programming typeclass