0

Imagine the 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 is 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 is not in scope, obviously
    }
}

Now, of course there are solutions to this.

One being "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
}

Another one being "put everything in one method", so basically merge setupButton() and setupTable(). That is a nogo if the stuff going on in these methods is a bit more complex tho.

Another one would be to give the methods parameters like:

private void setupTable(b: Button) {...}

All of my proposed solutions seem inappropriate, the first nearly always (why use a var, if you only need a val?) and the second in most cases. The thirds leads to unnecessary code that is just there so we get into scope what we need there.

I'm sure I could come up with multiple other solutions, but I ask you: What would you do in such a case?

1 Answer 1

2

Refactor setupXXX method and return created component:

val button = setupButton()
val table = setupTable()

or without auxiliary methods:

val button = { // setup button
}
val table = {  // setup table
}
Sign up to request clarification or add additional context in comments.

2 Comments

That works good if you only do one button. But if I have a method called "setupTableS()" (see the plural) then I would have to do one for each table? (Would be the same without auxiliary methods)
@Teolha if you can't separate setup of components you could use setup method like following: val (table1, table2) = setupTables() e.g.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.