想象一下下面的 Java 类:
class Test
{
private Button b;
private Table t;
public Test()
{
setupButton();
setupTable();
}
private void setupButton()
{
b = ...
b.doAwesomeStuff();
// ... more stuff going on
}
private void setupTable()
{
t = ...
t.attach(b); // Works, because b is in (class) scope
}
}
Scala 中的相同代码:
class Test()
{
setupButton();
setupTable();
private def setupButton(): Unit =
{
val button: Button = ...
}
private def setupTable(): Unit =
{
val table: Table = ...
table.attach(button) // <--- error, because button is not in scope, obviously
}
}
现在,当然有解决方案。
其中之一是“使用变量”:
class Test
{
private var b: Button = _
private var t: Table = _
// ... Rest works now, because b and t are in scope, but they are vars, which is not necessary
}
另一个是“将所有内容放入一个方法中”,因此基本上合并 setupButton() 和 setupTable()。如果这些方法中发生的事情有点复杂,那就不行了。
另一种方法是为方法提供参数,例如:
private void setupTable(b: Button) {...}
我提出的所有解决方案似乎都不合适,第一个几乎总是(如果您只需要一个 val,为什么使用 var?),第二个在大多数情况下。第三个导致不必要的代码就在那里,所以我们进入了我们需要的范围。
我确信我可以想出多种其他解决方案,但我问你:在这种情况下你会怎么做?
最佳答案
重构setupXXX
方法并返回创建的组件:
val button = setupButton()
val table = setupTable()
或者没有辅助方法:
val button = { // setup button
}
val table = { // setup table
}
关于java - Scala 范围、初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30567017/