【发布时间】:2012-05-11 21:54:41
【问题描述】:
我几天来一直在研究隐式转换的问题,但不知何故,我无法弄清楚我做错了什么。我通读了关于 SO 的所有其他涉及隐式的问题,但我仍然不明白问题是什么。
作为一个例子,让我们考虑一个这样的Java接口(为了简洁,T扩展了Object):
public interface JPersistable<T extends Object> {
public T persist(T entity);
}
在 scala 中,我执行以下操作:
case class A()
case class B() extends A
case class C()
case class D() extends C
trait Persistable[DTOType <: A, EntityType <: C] {
// this would be implemented somewhere else
private def doPersist(source: EntityType): EntityType = source
// this does not implement the method from the Java interface
private def realPersist(source: DTOType)(implicit view: DTOType => EntityType): EntityType = doPersist(source)
// this DOES implement the method from the Java interface, however it throws:
// error: No implicit view available from DTOType => EntityType.
def persist(source: DTOType): EntityType = realPersist(source)
}
case class Persister() extends Persistable[B, D] with JPersistable[B]
object Mappings {
implicit def BToD(source: B): D = D()
}
object Test {
def main(args: Array[String]) {
import Mappings._
val persisted = Persister().persist(B())
}
}
如评论中所述,我在编译时遇到异常。我想我的问题是:
1) 为什么我需要在doRealPersist 上显式指定隐式转换?即使我执行以下操作,我也预计会发生转换:
trait Persistable[DTOType <: A, EntityType <: C] {
// this would be implemented somewhere else
private def doPersist(source: EntityType): EntityType = source
def persist(source: DTOType): EntityType = doPersist(source)
}
但是,这也不能编译。
2) 为什么编译在persist 而不是在实际方法调用(val persisted = Persister().persist(B()))处失败?那应该是第一个知道 EntityType 和 DTOType 的实际类型的地方吧?
3) 有没有更好的方法来做我想要实现的目标?同样,这不是我想要做的实际事情,但已经足够接近了。
如果这个问题是无知的,请提前道歉,并提前非常感谢您的帮助。
【问题讨论】:
标签: scala generics implicit-conversion