scala中的隐式转换有问题
有这个代码吗scala中的隐式转换有问题,scala,implicit-conversion,json4s,Scala,Implicit Conversion,Json4s,有这个代码吗 case class Workspace(ident: Long, name: String) case class Project(ident: Long, name: String) implicit def workspaceJSON: JSONR[Workspace] = new JSONR[Workspace] { def read(json: JValue) = Workspace.applyJSON(field[Long]("id"), field[St
case class Workspace(ident: Long, name: String)
case class Project(ident: Long, name: String)
implicit def workspaceJSON: JSONR[Workspace] = new JSONR[Workspace] {
def read(json: JValue) =
Workspace.applyJSON(field[Long]("id"), field[String]("name"))(json)
}
implicit def projectJSON: JSONR[Project] = new JSONR[Project] {
def read(json: JValue) =
Project.applyJSON(field[Long]("id"), field[String]("name"))(json)
}
def parseEnt[T: JSONR](json: JValue): Either[String, T] =
fromJSON[T](json).toEither.left.map{ _.toString }
def fetchProjects(ws: Workspace): Either[String, Project] = {
parseEnt(parse("some text"))
}
无法在parseEnt(解析(“某些文本”)
上使用
ambiguous implicit values: both method taskJSON in class Fetcher of type =>
Fetcher.this.JSONR[types.Task] and method workspaceJSON in class Fetcher of type =>
Fetcher.this.JSONR[Fetcher.this.Workspace] match expected type Fetcher.this.JSONR[T]
有没有办法确保scala,在这种情况下,我希望类型变量
T
成为Project
并选择projectJSON
函数来解析它?或者,如果我做得不对,那么如何以正确的方式进行呢?编译器正在尝试自动推断类型T
,这一定是可以从字符串开始生成的内容(或多或少,但这里的细节不重要)
不幸的是,它无法成功,因为您提供了从String
到Project
和Workspace
的多个隐式转换。简单的解决方案是明确指出您试图生成的类型:
parseEnt[Project](parse("some text"))
这种模式在序列化类型类中相当常见,在序列化类型类中,您将多个特定类型映射到一个泛型类型(String
)?parsent[Project](parse(“some text”))我知道编译器对于使用哪个实例是不明确的,但我觉得奇怪的是,它不能从函数类型推断类型fetchProjects
,我认为在这种情况下t
应该是Project
。似乎我必须阅读更多关于scala中的类型推断和隐式的内容。