As a longtime Java programmer, and in recent years I have been using Haskell, I am learning Scala now.
Congratulations :)
How to program without side effects in Java? How can I do manually what Scala does for me?
Well, Scala doesn't do so much for you (compared to Haskell) in terms of providing or supporting a free-style side effect. For example, you always have the Scala option to use var
, wherever you are, whereas in Haskell, if you want to change IORef
or STRef
, you need to specify this in the type system using the appropriate monad.
In other words, although you are asking how to simulate the Scala style in Java, the first step to consider is how to simulate the Haskell style in Scala, which of course is Scalaz .
All that was said, I think that you basically answered your question:
I assume that many of the well-known advantages can be obtained using simple old java and a little discipline (for example, non-modifiable collections, final values, hard methods that do not change the state of the object / application).
Discipline is at least half the story. Just using final
and immutable collections (à la Guava ) has all sorts of consequences for what your code looks like. The other half of the story, of course, is what you do when your program requires side effects (such as I / O)? In Haskell you have to use the IO
monad, and in Scala you can use scalaz.effects.IO
, but in Java, to be honest, I think the battle is not worth the fight.
In my opinion, the two most important lines of functional style code that you will write in any Java program are as follows:
import static com.google.common.collect.Iterables.filter; import static com.google.common.collect.Iterables.transform;
The rest is an exercise for the reader;)