Scala method where type of second parameter equals part of generic type from first parameter
Asked Answered
R

1

5

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)
Roswell answered 18/6, 2010 at 10:4 Comment(0)
W
9

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

def genericFind[T](attribute:SingularAttribute[Person, T], value:T) {
  ...
}
Women answered 18/6, 2010 at 10:10 Comment(5)
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?Roswell
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.Drawing
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! ThanksRoswell
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 ).Drawing
...although I should note that you would use variance in Scala if you controlled the "attribute" class, see here: scala-lang.org/node/129Drawing

© 2022 - 2024 — McMap. All rights reserved.