Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I translate Scala traits to java?

Tags:

scala

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.

like image 501
deltanovember Avatar asked Aug 02 '26 14:08

deltanovember


2 Answers

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.

like image 67
Andrzej Doyle Avatar answered Aug 04 '26 12:08

Andrzej Doyle


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 ...
};
like image 37
jpalecek Avatar answered Aug 04 '26 12:08

jpalecek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!