For example suppose I have
abstract class OrderRout开发者_如何学编程er 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 ...
};
You have to use composition:
class NYSE implements Market {
void methodA() {
//implementation
}
}
interface Market {
void methodA();
}
class OrderRouter implements Market {
Market market;
OrderRouter(Market m) {
this.market = m;
}
// for each method in market implements it and
// redirect the call to this.market
public void methodA() {
market.methodA();
}
}
And then:
OrderRouter or = new OrderRouter(new NYSE());
精彩评论