flamecto
flamecto

Reputation: 139

How to call a Scala method that has Numeric parameter from Java

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

Answers (2)

Alexey Romanov
Alexey Romanov

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 Numerics without modifying it.

Upvotes: 1

Tim
Tim

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

Related Questions