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

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?


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:

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

    func makeIncrementer(forIncrement amount: Int) -> () -> Int {
        var runningTotal = 0
        return () -> Int {
            runningTotal += amount
            return runningTotal
        }
    }
    
  • (minor) Closures support shorthand argument names, eg

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

    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, eg java.util.Comparator that defines a bunch of convenient methods for comparator building, such as reversed and thenComparing .


    I can only think of one restriction in the Java functional API.

    In order to write a lambda expression in Java, you must need an interface with one method. There are already some interfaces made for you in the JDK, but IMHO, their names are less descriptive than the swift's function types. You can't guess immediately that Predicate<T> accepts a T parameter and returns a boolean . On the other hand, T -> Bool is much cleaner and clearer.

    I think other than that, Java's lambda expressions can do anything that swift function types can.


    我认为,在任何情况下,我都必须学习,作为Java开发人员,我可以说功能性编程是一个难以理解的主题,但我现在了解了很多功能,我不知道您是否可以在SWIFT中使用流当使用闭包时,一旦你获得了函数接口以及如何实现lambda表达式,你将会意识到,你可以用lambda / streams组合方式以更可读的方式用几行代码来做很多事情,我认为oracle已经把很多努力,如果你使用得好,你可以做出更清洁,更好的代码,回答你的问题都是强大的,但我同意lambdas更类似于迅速关闭。

    链接地址: http://www.djcxy.com/p/96388.html

    上一篇: angular2:如何在保持重定向网址的同时获取CanLoad守卫的完整路径

    下一篇: 将Java的lambda表达式与Swift的函数类型进行比较