5

I have this in scala:

object Tester {
  def apply[T : Manifest](description: String, initValue: T) = new Tester[T](description, initValue)
  implicit def TesterToValue[T](j: Tester[T]): T = j.value
}

class Tester[T : Manifest](someData: String, initValue: T) {
  private var value = initValue
  def getValue : T = value
}

which allows me to do

val t1 = JmxValue("some data", 4)

I'm trying to create an instance of this is java, so far I've had no luck I've tried:

Tester t1 = Tester<Integer>("data", 0);
Tester<Integer> t1 = Tester<Integer>("data", 0);
Tester t1 = Tester("data", 0);
Tester t1 = new Tester<Integer>("data", 0);
Tester<Integer> t1 = new Tester<Integer>("data", 0);

Is there some limitation in using scala generic classes in java? Or am I just doing something horribly wrong

1
  • For starters, you can strike all of the attempts that don't use new. Tester t1 = Tester<Integer>("data", 0); isn't syntactically valid Java under any circumstance (that doesn't even have anything to do with Scala). Commented Feb 13, 2014 at 23:18

1 Answer 1

6

Your Tester class actually has an implicit parameter (because of the [T : Manifest] type boundary. The syntax you use is sugar for

// Scala Class
class Tester[T](someData: String, initValue: T)(implicit man: Manifest[T]){...}

When that gets compiled, the two argument lists are condensed to one, so you end up with the java equivalent of

//Java Constructor
public Tester(String someData, T initValue, Manifest<T> man){...}

You can see the type signature by running the javap command on the Tester.class file that gets generated by the scala compiler.

So if you are trying to use the Tester class from Java, you have to explicitly figure out the parameter that scala's compiler would normally figure out for you.

Looking at the scaladocs, it looks like ManifestFactory is where you need to go to create Manifest instances. So your java code would look something like

Manifest<Integer> man = ManifestFactory$.MODULE$.classType(Integer.class);
Tester<Integer> tester = new Tester<Integer>("data", 123, man);
Sign up to request clarification or add additional context in comments.

3 Comments

I edited my answer a little while ago. The example I added should answer that question.
I will trust that this will work, but upon further investigation this requires latest version of scala?
I think in older versions of Scala there was a Manifest companion object that had factory methods for Manifests. Poke around in the docs to find what you need.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.