title: Pure functions and Java
body: <p>I have several doubts about Java and pure functions. As far as I know, a pure function is a function for which these two statements hold:</p>
  
  <ol>
  <li>No side-effects.</li>
  <li>Same results given the same input.</li>
  </ol>
  
  <p>According to that (and as an example), this function would be pure:</p>
  
  <pre><code>int sum(int a, int b) { return a + b; }
  </code></pre>
  
  <p>However, <strong>would this function be considered pure?</strong></p>
  
  <pre><code>int sum(Person a, Person b) { return a.getAge() + b.getAge(); }
  </code></pre>
  
  <p>My guess is no, because the result is different depending on the Person objects that you pass as parameters to the function.</p>
  
  <p>Taking into account that objects in Java (and OO languages in general) have hidden information, <strong>could any function that involves objects as parameters be considered pure?</strong></p>
  
  <p>Another question, <strong>can a language/program be considered pure if any of its functions is not pure?</strong></p>
  
  <p>Taking into consideration all this, <strong>could a Java program (fairly complex) be composed only of pure functions (be pure, so to say) or is it just something impossible?</strong></p>
  
  <p>Another question, as far as the compiler is concerned, a lambda expression can only use final (or effectively final) variables:</p>
  
  <pre><code>// Correct
  int f = 0;
  IntStream.of(1,2,3).map(e -&gt; e * f).forEach(System.out::println);
  
  // Compilation error
  int g = 0;
  IntStream.of(1,2,3).map(e -&gt; e * g).forEach(System.out::println);
  g = 22;
  </code></pre>
  
  <p><strong>How is it possible that that being the case this code compiles?</strong></p>
  
  <pre><code>// Correct
  int[] f = new int[]{ 0 };
  IntStream.of(1,2,3).map(e -&gt; e * f[0]).forEach(System.out::println);
  f[0] = 25;
  </code></pre>