For example suppose I have
abstract class OrderRouter extends Market {
}
I would normally instantiate as follows
new OrderRouter with NYSE
How would I translate the above line into java? NYSE is a trait which extends Market.
Have a look at the question How are Scala traits compiled into Java bytecode?, and the accepted answer.
The summary is that, assuming NYSE has a getOrderBook() method, the Java version would look like:
new OrderRouter() {
public OrderBook getOrderBook() {
return NYSE$class.getOrderBook();
}
}
The Scala compiler generates bytecode for synthetic classes, which mix in all of the trait implementations via composition/wrapping. Since javac doesn't have this feature, you need to wire in the delegation of trait methods to the trait's singleton object yourself.
I believe the best option for translating scala code to java is using a scala compiler and using the resulting class files from java.
There is no direct translation of traits into java. Even the scala compiler basically copies code from the trait to the concrete class, and you'll have to do it too:
abstract class A { void foo(); }
/* trait T {
void boo() { ... code ... }
}
*/
// This would be
// A with T
class AwithT extends A
{
// copied from T
void boo() { ... code ... }
// other definitions ...
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With