Reputation: 139
I have a Scala method that takes a Numeric[T]
object:
def needNumeric[T](value: T)(implicit n: Numeric[T]) = {
// do something
}
How do I call this method from Java? The best way I've come up with is this:
needNumeric(0, scala.math.Numeric.IntIsIntegral$.MODULE$);
But the code looks ugly and is not very general. Is there a better way to do it?
Upvotes: 0
Views: 241
Reputation: 170723
A slight workaround for the ugliness issue: define Java-convenient access like
class Numerics {
public static final Numeric<Integer> INTEGER = Numeric.IntIsIntegral$.MODULE$;
public static final Numeric<Double> DOUBLE = Numeric.DoubleIsFractional$.MODULE$;
...
}
The tradeoff is that it allows calling any method requiring Numeric
s without modifying it.
Upvotes: 1
Reputation: 27356
Java supports polymorphic methods, so how about something like this:
object original {
def needNumeric[T](value: T)(implicit n: Numeric[T]) = {
// do something
}
}
object NeedNumeric {
def needNumeric(value: Int) = original.needNumeric(value)
def needNumeric(value: Long) = original.needNumeric(value)
def needNumeric(value: Float) = original.needNumeric(value)
def needNumeric(value: Double) = original.needNumeric(value)
def needNumeric(value: BigInt) = original.needNumeric(value)
...
}
import NeedNumeric._
It is tedious to have to enumerate the types (which is why the Scala uses a type class) but it should be OK for numerical values as there aren't very many numeric types.
If this is your own needNumeric
method then note that the signature can be simplfied to this:
def needNumeric[T: Numeric](value: T) = {
Upvotes: 3