Scala用大括号实例化一个类
我从Scala和ScalaFX开始,我理解大部分代码,但我不理解ScalaFX中示例使用的代码 在实例化一个匿名类之后加上花括号的地方,这是如何工作的Scala用大括号实例化一个类,scala,scalafx,Scala,Scalafx,我从Scala和ScalaFX开始,我理解大部分代码,但我不理解ScalaFX中示例使用的代码 在实例化一个匿名类之后加上花括号的地方,这是如何工作的 object ScalaFXHelloWorld extends JFXApp { stage = new PrimaryStage { title = "ScalaFX Hello World" scene = new Scene { fill = Black content = new H
object ScalaFXHelloWorld extends JFXApp {
stage = new PrimaryStage {
title = "ScalaFX Hello World"
scene = new Scene {
fill = Black
content = new HBox {
padding = Insets(20)
children = Seq(
new Text {
text = "Hello"
style = "-fx-font-size: 48pt"
fill = new LinearGradient(
endX = 0,
stops = Stops(PaleGreen, SeaGreen)
)
},
new Text {
text = "World!!!"
style = "-fx-font-size: 48pt"
fill = new LinearGradient(
endX = 0,
stops = Stops(Cyan, DodgerBlue)
)
effect = new DropShadow {
color = DodgerBlue
radius = 25
spread = 0.25
}
}
)
}
}
}
}
我不明白的是,为什么在创建一个匿名类的过程中,后面跟着花括号(还有一些声明)(场景不是填充该类抽象部分的轨迹),甚至fill或content都是函数而不是变量,Black for fill for instant是val,意思是这一行
fill = Black
正在调用函数fill并为其分配val(对我来说没有意义),这是fill定义
def fill: ObjectProperty[jfxsp.Paint] = delegate.fillProperty
这是黑色的
val Black = new Color(jfxsp.Color.BLACK)
如何使用花括号实例化新对象请帮助,希望了解。
这是因为ScalaFx正在包装JavaFx,并且这里发生了一些特别的事情?。
谢谢你们
更新:
现在我知道它是通过语法糖调用setter,但是我检查了setter,我不明白那里发生了什么
请查看:
def fill: ObjectProperty[jfxsp.Paint] = delegate.fillProperty
def fill_=(v: Paint) {
fill() = v
}
为什么setter调用getter来更新值
delegate.fillProperty
是一个返回值的函数Scala中匿名类的语法借用自Java;你也可以在这里看到:
class Coder {
protected String name;
public Coder(String name) {this.name = name;}
}
public static void main(String[] args) {
// Prints "Mr. Noble"
new Coder("Noble") {
private String prefix = "Mr.";
{
System.out.println(prefix + " " + name);
}
}
}
因为Scala允许您在类主体中编写构造函数代码,所以当您实例化这些匿名类时,所有的x=y
语句都会执行。正如@resueman指出的,这些实际上是这种格式的getter和setter:
class Scene {
var _fill
def fill_=(color: Color) // Setter, has some hidden logic to set up the UI
def fill = _fill // Getter
}
您的语句fill=Black
将被删除为fill_u=(Black)