Using the scala generic class in java

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
}

what allows me to do

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

I am trying to create an instance of this java, so far I have not been lucky I 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 any limitation when using scala common classes in java? Or am I just doing something terribly wrong

+4
source share
1 answer

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

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

When this compiles, two argument lists are compressed to one, so you get the java equivalent

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

, javap Tester.class, scala.

, Tester Java, , scala .

, ManifestFactory, . , Java- :

Manifest<Integer> man = ManifestFactory$.MODULE$.classType(Integer.class);
Tester<Integer> tester = new Tester<Integer>("data", 123, man);
+5

Source: https://habr.com/ru/post/1526834/


All Articles