Assume this simple trait. A trait which exposes a val x. Since the initialization costs of x are very high I choose val x =... over def x =...
trait ScalaTrait {
self =>
val x: Int = SomeVeryExpensiveOperation.do()
}
Now how about a Java class implementing this trait. I'm of course obliged to implement val x using a public method in my Java class. But here is the catch: because the public method and my trait's val x share the same name I can't just delegate to the trait implementation:
class JavaClass imlements ScalaTrait {
@Override
public x() {
/* I can't hand over this call to x() of the trait,
since this would be a recursive call inside the Java class itself*/
return x(); <-- so, this no can do!
}
}
My question is what exactly should go inside method x()?
As an alternative I could provide a public def accessor to that private val x field. Like so:
trait ScalaTrait {
self =>
private val _x: Int = SomeVeryExpensiveOperation.do()
def x = _x
}
But still, I'm now forced to implement that private val _x in my Java class, too, regardless of the private access modifier. How can I make this work and why must my Java class implement the private val field in the first place?