3

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.

Didier Dupont
  • 29,398
  • 7
  • 71
  • 90
Timo Westkämper
  • 21,824
  • 5
  • 78
  • 111

2 Answers2

4

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)
Alexey Romanov
  • 167,066
  • 35
  • 309
  • 487
3

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)
Didier Dupont
  • 29,398
  • 7
  • 71
  • 90
  • It doesn't seem to work. Try this : val conv: RelationalPathAdapter[User,QUser] = toAdapter(path) – Timo Westkämper Nov 19 '11 at 19:37
  • Still, it answers your original question, as you can do `path.someMethod`. But good point, the information about `QUser` is lost, you have only `RelationalPathAdapter[User, RelationalPath[User]]`. Alexey's solution it is then. – Didier Dupont Nov 19 '11 at 21:35
  • Yes, my question was not explicit enough. Thanks for your efforts though. – Timo Westkämper Nov 20 '11 at 08:45