想象一下以下Java类:
Queue
Scala中的相同代码:
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
}
}
现在,当然有解决方案。
一个人正在使用vars":
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
}
}
另一个是&#34;将所有内容放在一个方法&#34;中,所以基本上合并setupButton()和setupTable()。如果这些方法中发生的事情有点复杂,那就是nogo。
另一种方法是给出方法参数,如:
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
}
我提出的所有解决方案似乎都不合适,第一个几乎总是(为什么使用var,如果你只需要一个val?)而在大多数情况下是第二个。三分之一导致不必要的代码就在那里,所以我们进入了我们需要的范围。
我确定我可以提出其他多种解决方案,但我问你:在这种情况下你会做什么?
答案 0 :(得分:3)
重构repositories {
maven { url "http://repo.spring.io/snapshot" }
maven { url "http://repo.spring.io/milestone" }
}
方法并返回创建的组件:
setupXXX
或没有辅助方法:
val button = setupButton()
val table = setupTable()