Note that there are some explanatory texts on larger screens.

plurals
  1. POScala implicit conversion on generic trait implementing Java interface
    text
    copied!<p>I have been working on an issue with implicit conversion for days now, but somehow I just cannot figure out what I am doing wrong. I read through all the other questions on SO that deal with implicits but I still don't understand what the problem is.</p> <p>As an example, let's consider a Java interface like this(T extends Object for brevity):</p> <pre><code>public interface JPersistable&lt;T extends Object&gt; { public T persist(T entity); } </code></pre> <p>In scala, I do the following:</p> <pre><code>case class A() case class B() extends A case class C() case class D() extends C trait Persistable[DTOType &lt;: A, EntityType &lt;: 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 =&gt; EntityType): EntityType = doPersist(source) // this DOES implement the method from the Java interface, however it throws: // error: No implicit view available from DTOType =&gt; 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()) } } </code></pre> <p>As stated in the comment, I get an exception at compile time. I guess my questions are:</p> <p>1) Why do I need to specify the implicit conversion on the <code>doRealPersist</code> explicitly? I expected the conversion to happen even if I do the following:</p> <pre><code>trait Persistable[DTOType &lt;: A, EntityType &lt;: C] { // this would be implemented somewhere else private def doPersist(source: EntityType): EntityType = source def persist(source: DTOType): EntityType = doPersist(source) } </code></pre> <p>However, this does not compile either.</p> <p>2) Why does compilation fail at <code>persist</code> and not at the actual method call (<code>val persisted = Persister().persist(B())</code>)? That should be the first place where the actual type of EntityType and DTOType are known, right?</p> <p>3) Is there a better way to do what I am trying to achieve? Again, this is not the actual thing I am trying to do, but close enough.</p> <p>Apologies in advance if this question is ignorant and thanks a lot in advance for your help.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload