Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java function with "..." in parameter list from Scala

As described here

If you want to make the code compile you have to add the :_* keyword to the condition:Predicate

Now I have this problem

val queryBuilder = em.getCriteriaBuilder()
     val cq = queryBuilder.createQuery(classOf[Product])
     val product:Root[Product] = cq.from(classOf[Product])
     val condition:Predicate = queryBuilder.equal(product.get("name"), "name")
     --> cq.where(condition:_*)


Multiple markers at this line
- type mismatch; found : javax.persistence.criteria.Predicate required: Seq[?]

Any idea?

like image 696
Massimo Ugues Avatar asked Dec 17 '22 10:12

Massimo Ugues


1 Answers

You must not use :_* here.

There reason why _* exists is that varargs may lead to ambiguities. In java If you have f(int... values) you may call f(1, 2, 3), but also have do

int[] values = {1, 2, 3}; 
f(values)

With ints, it is ok. But if you have f(object.. values) and have object[] values = {"a", "b"}, when calling f(values), should it means that f is called with a single arg, which is the values, or with multiple args "a" and "b"? (java chooses the later).

To avoid that, in scala, when there are varargs, it is not allowed to pass them as arrays (actually the more general Seq in scala) argument, except if you explicitly says you are doing so, by putting the abscription :_*. With the previous example, f(values) means values is the single argument. f(values: _*) means each element of values, whether there are zero, one, or many, is an argument.

In your particular case, you are passing the Predicate arguments (actually just one) as separate (well...) predicates, not as a collection of predicates. So no :_*

Edit: I read the post you linked to more carefully. While what I certainly believe what I have written above is true, it is probably not helpful. The proper answer was given by MxFr:

  1. Since scala 2.9, interaction with java varargs is ok. just pass condition
  2. Before that, you must pass your arguments as an array, and put :_*
like image 140
Didier Dupont Avatar answered Dec 29 '22 07:12

Didier Dupont