Scala 范围,初始化
Scala scope, initialization
假设如下 Java Class:
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
}
}
现在,当然有解决办法。
一个是 "use vars":
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
}
另一个是 "put everything in one method",所以基本上合并 setupButton() 和 setupTable()。如果这些方法中发生的事情有点复杂,那就不行了。
另一种方法是为方法提供如下参数:
private void setupTable(b: Button) {...}
我提出的所有解决方案似乎都不合适,第一个几乎总是(如果只需要一个 val,为什么要使用 var?),大多数情况下都是第二个。三分之二导致不必要的代码就在那里,所以我们进入我们需要的范围。
我确定我可以想出多种其他解决方案,但我问你:在这种情况下你会怎么做?
重构 setupXXX
方法和 return 创建的组件:
val button = setupButton()
val table = setupTable()
或无辅助方法:
val button = { // setup button
}
val table = { // setup table
}
假设如下 Java Class:
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
}
}
现在,当然有解决办法。
一个是 "use vars":
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
}
另一个是 "put everything in one method",所以基本上合并 setupButton() 和 setupTable()。如果这些方法中发生的事情有点复杂,那就不行了。
另一种方法是为方法提供如下参数:
private void setupTable(b: Button) {...}
我提出的所有解决方案似乎都不合适,第一个几乎总是(如果只需要一个 val,为什么要使用 var?),大多数情况下都是第二个。三分之二导致不必要的代码就在那里,所以我们进入我们需要的范围。
我确定我可以想出多种其他解决方案,但我问你:在这种情况下你会怎么做?
重构 setupXXX
方法和 return 创建的组件:
val button = setupButton()
val table = setupTable()
或无辅助方法:
val button = { // setup button
}
val table = { // setup table
}