tags:

views:

31

answers:

1

I just solved the first problem from Project Euler in JavaFX for the fun of it and wondered what block expressions are actually good for? Why are they superior to functions? Is it the because of the narrowed scope? Less to write? Performance?

Here's the Euler example. I used a block here but I don't know if it actually makes sense

// sums up all number from low to high exclusive which are divisible by a or b
function sumDivisibleBy(a: Integer, b: Integer, high: Integer) {
    def low = if (a <= b) a else b;

    def sum = {
        var result = 0; 

        for (i in [low .. <high] where i mod a == 0 or i mod b == 0) {
            result += i
        }

        result
    }
}

Does a block make sense here?

+1  A: 

Well, no, not really, it looks like extra complexity with no real benefit. Try removing the sum variable and the block and you will see that the code still works the same.

In general block expressions can be useful when you want to create an anonymous scope rather than factoring the code into a function, most of the time you should rather create a function.

Honza