일 동안 암시 적 변환 문제를 해결하기 위해 노력했지만 어떻게 든 잘못 이해하고 있습니다. 나는 암시를 다루는 다른 모든 질문을 읽었지 만 나는 아직도 그 문제가 무엇인지 이해하지 못한다.자바 인터페이스를 구현하는 일반적인 특성에 대한 스칼라 암시 적 변환
예를 들어, 이제 (T는 간결 객체를 확장)과 같은 Java 인터페이스를 살펴 보자 : 주석에 명시된 바와 같이
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())
}
}
:
스칼라public interface JPersistable<T extends Object> {
public T persist(T entity);
}
, 나는 다음을 수행 , 나는 컴파일 타임에 예외를 얻는다. 제 질문은 다음과 같습니다.
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) 실제 메서드 호출 (val persisted = Persister().persist(B())
)이 아닌 persist
에서 컴파일이 실패하는 이유는 무엇입니까? EntityType과 DTOType의 실제 유형이 알려진 첫 번째 장소 여야합니다. 맞습니까?
3) 달성하려는 작업을 수행하는 더 좋은 방법이 있습니까? 다시 말하지만, 이것은 내가하려고하는 실제적인 것이 아니라 충분히 가깝습니다.
이 질문이 무식하고 사전에 도움을 주시면 감사하겠습니다.
렉스 Rex. 아직도 혼란스러운 것은 Predef implicits ('byte2short'와 같은)를 위해서 당신이 변환을 사용하기를 원한다면 그 추상 def를 지정할 필요가 없다는 것입니다. 나는 전환이 가능할 것이라고 예상했다. .. 음, 암시 적으로. 특히 내 질문에 1, 유형을 알고 변환을 해결하기 위해 scala를 기대합니다. 최소한 필자가 예로 든 Persister의 범위에'Mappings._'을 가져 오면 암묵적인 def를 다시 구현할 필요가 없다는 것을 나는 기대할 것이다. 그것은 정확히 내가 잘못하고있는 것이 무엇인지 내게 미스테리가 남아있다 ... – LeChe
@LeChe - 나는 "외부 암시 적 변환을해라."라는 조언을 사용하여 제 답변을 업데이트했습니다. –
물론, 나는 그런 바보 야! 특성이 A-tree를 알아야하는 이유는 무엇입니까? 변환은 완전히 투명해야합니다. 젠장, 지금 바보 같아. 당신의 설명에 진심으로 감사드립니다. – LeChe