问题
Is this statement true that Java 8 provides functional style but is not functional programming as the syntax which it uses is also an object?
Calculator calc = (i, j) -> i/j;
If yes, then why we get articles everywhere Functional Programming with Java 8?
回答1:
Here is a (non-exhaustive) list of abstract FP concepts:
- Focus on immutability
- Referential transparency for functions
- Limitations on side effects (follows from 1 & 2)
- Expression-based, no statements. Statements are not first-class.
- Functions as first-class values.
- State changes as first-class values (e.g. Clojure atoms).
- Algebraic Data Types as fundamental units.
- Enforcing some or all of the above via the type system.
And I could go on. A language doesn't have to tick every box on the list to be a "Functional Programming Language" (I can't actually think of any that meet all of those bullet points), but the more boxes it ticks the less qualification you have to give to give it that label. And that's why Java doesn't qualify in the eyes of many functional programmers: it just doesn't check off very many (arguably only one) of the above items.
Which is not to say that you cannot do functional programming in Java, but it's hard. The language gives you too few of the tools you need to work with, meaning you'll have to write a lot of boilerplate to encode the necessary primitives as classes, meaning your code will be slower and harder to follow (and that's before you get into the issue of 15 different competing ad-hoc library implementations of those primitives).
You can treat your objects as immutable, favor expressions over statements (like using the ternary operator instead of if/else), make most of your methods pure functions, go hog-wild with lambdas, etc. but at the end of the day there's still a lot of friction, both with the language and the expectations of the community.
来源:https://stackoverflow.com/questions/58658878/is-this-statement-true-that-java-8-provides-functional-style-but-is-not-function