代码之家  ›  专栏  ›  技术社区  ›  helpermethod

块表达式实际上有什么用?

  •  1
  • helpermethod  · 技术社区  · 16 年前

    为了好玩,我刚刚解决了JavaFX中ProjectEuler的第一个问题,我想知道块表达式实际上对什么有用?为什么它们优于功能?是因为范围缩小了吗?少写?性能?

    这是欧拉的例子。我在这里用过一个街区,但我不知道它是否真的有意义

    // 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
        }
    }
    

    这里的街区有意义吗?

    1 回复  |  直到 16 年前
        1
  •  1
  •   Honza    16 年前

    嗯,不,不是真的,它看起来是额外的复杂性,没有真正的好处。尝试删除sum变量和块,您将看到代码仍然工作相同。

    一般来说,当您希望创建匿名作用域而不是将代码分解为函数时,块表达式是有用的,大多数时候您应该更愿意创建函数。

    推荐文章