Tony Stark Tony Stark - 9 months ago 47
Swift Question

comparing java's lambda expression with swift's function type

In swift, function types are treated as first class citizen and can be used anywhere as any other types. Its syntax is straight forward and can be easily understood and used.

On the other hand, java does support function programming via lambda, but in general, i found it less initiative, harder to understand, and seemingly more restrictive compare to swift's function type.

My question is, since the purpose of swift's function type and java's lambda expression is to achieve functional programming, is there anything that the swift's function type can do, but java's lambda expression can't? or they are both equally powerful?

Answer Source

It is incorrect to compare Java's lambdas (implementation) and Swift's functional type (type). But it is possible to compare Java's lambda to Swifts's Closures. And Swift's functional type to Java's functional interfaces.

Closures are more powerful than lambdas:

  1. (major) Closures may capture non-constant variables, e. g

    func makeIncrementer(forIncrement amount: Int) -> () -> Int {
        var runningTotal = 0
        return () -> Int {
            runningTotal += amount
            return runningTotal
  2. (minor) Closures support shorthand argument names, e.g.

    reversedNames = names.sorted(by: { $0 > $1 } )
  3. (minor) Trailing closures support, e.g.

    someFunctionThatTakesAClosure() {
        // trailing closure's body goes here

From the other hand, functional interfaces are more powerful than functional types. They allows to declare additional methods, e.g. java.util.Comparator that defines a bunch of convenient methods for comparator building, such as reversed and thenComparing.