I tried
scala> class Foo extends Component { var font = new java.awt.Font("Helvetica", java.awt.Font.BOLD, 12) }
and I got:
<console>:10: error: overriding variable font in class Component of type java.awt.Font;
variable font needs `override' modifier
class Foo extends Component { var font = new java.awt.Font("Helvetica", java.awt.Font.BOLD, 12) }
^
So I tried
scala> class Foo extends Component { override var font = java.awt.new Font("Helvetica", java.awt.Font.BOLD, 12) }
but this didn’t help at all:
<console>:10: error: overriding variable font in class Component of type java.awt.Font;
variable font has incompatible type
class Foo extends Component { override var font = new java.awt.Font("Helvetica", java.awt.Font.BOLD, 12) }
^
What’s the reason behind this error and how should it be done correctly?
EDIT: Sorry, didn’t saw that scala also has Component. The Component in question is the one from java.awt.Component!
Component contains getters and setters for
font, so the canonical way to set the font is:If you want to override the font defs to use a var,
you have to use something compatible withscala.swing.Font, which wraps the Java fonts (normally done with implicit conversions). Like so:I’m not sure this will do what you want. (Edit: tested in a REPL session with too much junk loaded; you don’t actually need to do this! The simple override var font = new java.awt.Font thing works.) The normal getter/setter is designed to pass the information on through to the
javax.swingpeer. If you do it this way, you’ll probably break that forwarding. So use the first method.Edit if you are trying to do this in a
java.awt.Component:Font font;is a private field injava.awt.Component. You can’t override fields in Java, and you can’t do anything with private fields in Java. So trying to override it with a new var is guaranteed to not work. (The compiler could certainly give a more informative error message, however!) Scala can only override fields because they’re not really fields–they’re a getter/setter pair referring to a hidden underlying field.You should use (or override)
getFontandsetFontinstead.