I am translating code from Java to Scala and came across this:
JLabel l = new JLabel(label, JLabel.CENTER);
so I tried:
val l = new JLabel(trueLabel, JLabel.CENTER)
and the compiler tells me that CENTER is not a member. But looking at the source I have:
public class JLabel extends JComponent implements SwingConstants, Accessible
{
...
}
and
public interface SwingConstants {
/**
* The central position in an area. Used for
* both compass-direction constants (NORTH, etc.)
* and box-orientation constants (TOP, etc.).
*/
public static final int CENTER = 0;
Do I have to do anything from the Scala side to access this member?
I am using Scala 3 (Dotty)
I am using that, however I am assuming the implements should work. Note that if it does not work, this means we have to manually hunt down the definitions. This does not seem to be practical. Maybe I am missing something obvious?
In Java, interface fields are static, so they most naturally map to members in the companion object of a trait in Scala. While you can access static members via an object reference in Java, the (unmaintained?) code conventions state: “Avoid using an object to access a class (static) variable or method. Use a class name instead.” (§10.2)
So while I don’t know the actual mechanics at play in Java interop, I’m not terribly surprised that inheritance doesn’t seem to apply to Java interface fields when viewed from the Scala side.