Pregunta

I'm improving the Scala support in Querydsl and I encountered the following issue. Here is a code snippet that illustrates the problem :

// framework types  
class RelationalPath[T]
class RelationalPathAdapter[T, R <: RelationalPath[T]](p: R) { def someMethod = {} }

// domain types
class User  
class QUser extends RelationalPath[User]

implicit def toAdapter[T, R <: RelationalPath[T]](p: R) = new RelationalPathAdapter[T,R](p)

val path = new QUser()

toAdapter(path).someMethod // DOESN'T COMPILE

path.someMethod // DOESN'T COMPILE

How to match a type in a implicit conversion in addition to it's type argument. I can match either separately, but not both.

¿Fue útil?

Solución

In this specific case, the following change works:

implicit def toAdapter[T, R <: RelationalPath[T]](p: RelationalPath[T] with R) = 
  new RelationalPathAdapter[T,R](p)

Otros consejos

This is not really an implicit conversion issue, rather a type inference issue. When you call toAdapter(path), there is nothing implicit.

If you pass the type parameter, it works.

toAdapter[User, QUser](path).someMethod

It can even work with an implicit conversion :

 (path: RelationalPathAdapter[User, QUser]).someMethod

but of course, this is rather useless.

The proper way to write the implicit is

implicit def toAdapter[T, R[X] <: RelationalPath[X]](p: R[T]) 
  = new RelationalPathAdapter[T, R[T]](p)
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top