views:

88

answers:

1

I want to create a specific generic method in Scala. It takes two parameters. The first is of the type of a generic Java Interface (it's from the JPA criteria query). It currently looks like this:

def genericFind(attribute:SingularAttribute[Person, _], value:Object) {
  ...
}

// The Java Interface which is the type of the first parameter in my find-method:
public interface SingularAttribute<X, T> extends Attribute<X, T>, Bindable<T>

Now i want to achieve the following: value is currently of type java.lang.Object. But I want to make it more specific. Value has to be the of the same type as the placeholder "_" from the first parameter (and so represents the "T" in the Java interface).

Is that somehow possible, and how?

BTW Sorry for the stupid question title (any suggestions?)

EDIT: added an addtional example which could make the problem more clear:

// A practical example how the Scala method could be called 

// Java class:
public class Person_ {
  public static volatile SingularAttribute<Person, Long> id;
}

// Calling the method from Scala:
genericFind(Person_.id, Long)
+7  A: 

Of the top of my head (I'm still starting with Scala):

def genericFind[T](attribute:SingularAttribute[Person, T], value:T) {
  ...
}
RoToRa
Wow, i'm deeply impressed ;) Thanks for the fast answer. Actually it seems to work. Scala rocks! BTW: not so important, but would that be also be possible in Java?
ifischer
Yes, it's possible in Java too, it would be the following: "public <T> Person genericFind( SingularAttribute< Person, T > attribute, T value ) { ... }". Hope this helps :). Note that there's some slight issues with this where, for example, you want to pass a subtype of T instead of an instance of exactly T. You can get around this with extra annotation but it's probably beyond what you need.
Calum
Ok, good to know that its possible in Java. Don't need that extra annotation, but i would like to know which it is anyway! Thanks
ifischer
I omitted it because this form highlights badly but you want something like: public <T> Person genericFind( SingularAttribute< Person, ? super T > attribute, T value ) {...}. In Scala I *think* the equivalent is: def genericFind[T]( attribute: SingularAttribute[Person,_ <: T], value: T ).
Calum
...although I should note that you would use variance in Scala if you controlled the "attribute" class, see here: http://www.scala-lang.org/node/129
Calum