Comparing Java's lambda expression with Swift's function type

Thor :

In Swift, function types are treated as first class citizens, and can be used anywhere, as any other types. Its syntax is straightforward, and can be easily understood and used.

On the other hand, Java does support function programming via lambda expressions, but in general, I have found it less intuitive, harder to understand, and seemingly more restrictive, compared 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 Swift's function type can do, but Java's lambda expression can't? Or are they both equally powerful?

kgeorgiy :

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.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=451719&siteId=1