Why not .NET-style delegates rather than closures in Java?

前端 未结 2 792
花落未央
花落未央 2021-02-02 13:39

OK, this is going to be my beating a dying horse for the 3rd time.

However, this question is different from my earlier two about closures/delegates, which asks about pla

相关标签:
2条回答
  • 2021-02-02 14:20

    Your question is ironic. You're wondering why the Java community is struggling with three different proposals for adding closures, and your suggested solution is to add a fourth option to the mix?

    But to answer your question:

    • The right forum for discussion is the mailing list of openjdk project lambda. This is not a place where suggestions are likely to influence that effort.

    • The type systems for C# and Java are significantly different, so the C# solution would not directly apply. For example, C# has declaration-site variance (in/out), while java has use-site variance (wildcards). Inference of lambda parameter types as specified in C# would not apply in Java.

    • The evolution of Java must remain backward compatible, but adding the delegate keyword would be a breaking change.

    • C# has three types of delegate expressions: the old one with the delegate keyword, statement lambdas with =>{, and expression lambdas. If the C# language team has it to do over again, we'd certainly not have this many forms. Why should Java adopt C#'s historical baggage?

    • Because C# generics operate over primitives, the Func<> and Action<> delegate types can be used as poor-man's structural function types. But in Java, generics are erased, work only over reference types, and types cannot be distinguished by their arity. Consequently Java would have to have a large number of distinctly-named "standard" function types to get the same effect. That would not be pretty.

    Overall, the C# solution does not adapt to a very natural solution in Java.

    0 讨论(0)
  • 2021-02-02 14:23

    C# has closures in addition to delegates. In my mind they are not same.

    delegate = function pointer.

    closure = {function, environment}. Way of defining an [anonymous] function and packaging it with its environment. Strictly speaking latter should only be called closure, the former being 'lambda expression'.

    0 讨论(0)
提交回复
热议问题