java - Scala scope, initialization -
imagine following 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 in (class) scope } }
the same code in 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 not in scope, } }
now, of course there solutions this.
one being "use vars":
class test { private var b: button = _ private var t: table = _ // ... rest works now, because b , t in scope, vars, not necessary }
another 1 being "put in 1 method", merge setupbutton() , setuptable(). nogo if stuff going on in these methods bit more complex tho.
another 1 give methods parameters like:
private void setuptable(b: button) {...}
all of proposed solutions seem inappropriate, first (why use var, if need val?) , second in cases. thirds leads unnecessary code there scope need there.
i'm sure come multiple other solutions, ask you: in such case?
refactor setupxxx
method , return created component:
val button = setupbutton() val table = setuptable()
or without auxiliary methods:
val button = { // setup button } val table = { // setup table }
Comments
Post a Comment