4

I have been struggling with functional programming concepts for a while. I read that in functional programming, variable immutability is a fundamental thing. You don't change the state of a variable.

But I can achieve the same effect in Java by using the keyword 'final'? So why cannot Java be used as a functional language?

gnat
  • 21,442
  • 29
  • 112
  • 288
Kaushik
  • 1,195
  • 3
  • 12
  • 20
  • Functions as first class objects is another major feature of functional languages. Are they, in Java? – Oded Sep 29 '15 at 15:05
  • 1
    see [Is Functional Programming possible in Java?](http://programmers.stackexchange.com/questions/101352/is-functional-programming-possible-in-java) – gnat Sep 29 '15 at 15:07
  • @oded: Well, they did manage to put in lambda expressions. I don't suppose interfaces with a single method count? – Robert Harvey Sep 29 '15 at 15:07
  • 3
    @Kaushik: Note that immutability is not the only characteristic of functional languages, so your initial premise (that a language can be used as a functional language if it has immutable variables) is kinda wrong. – Robert Harvey Sep 29 '15 at 15:10
  • 1
    Downvoter, please explain?? – Kaushik Sep 29 '15 at 15:20
  • 1
    There isn't enough explanation in the comments already? – Robert Harvey Sep 29 '15 at 15:23
  • 4
    @RobertHarvey gnat's comment is a link to a related question. Both your and Oded's comments are closer to answers than suggestions on how to improve the question. Having an incorrect premise isn't grounds for a downvote, it just means the OP has an incomplete understanding(which is why they're asking the question). – Shaz Sep 29 '15 at 15:39
  • The real trick to utilizing immutability to make your language functional is to use local state only - not sharing state across contexts except when you pass the value to other functions as a parameter. You want to use Java functionally? Use only final local variables of types that have only final members. In functional programming, everything should have it's *final* value, *immediately upon construction*. Also, you need to use functions as variables to compose functions, which is tricky at best, and irritating as hell at worst in Java. – Jimmy Hoffa Sep 29 '15 at 15:47

1 Answers1

4

Sure, you can do programming in a functional style in Java. It's just really difficult, because there's a lot more to it than just immutability. One of the big ones is first-class functions, (being able to treat a function reference as a variable, without it having to be tied to an object,) which the Java language has provided no functionality for up until very recently, when lambdas were introduced.

Even now that it's possible, there's still 20 years of legacy Java code hanging around that has no concept of functional programming, that your code will probably have to interact with, so that makes any use of it more difficult than it probably should be.

Mason Wheeler
  • 82,151
  • 24
  • 234
  • 309