sampottinger / processing

Source code for the Processing Core and Development Environment (PDE)
http://processing.org
Other
10 stars 1 forks source link

Keyword var in for loop not working #104

Closed hamoid closed 5 years ago

hamoid commented 5 years ago

Hi :) Is this expected?

ArrayList<PVector> vv = new ArrayList<>();

void setup() {
  vv.add(PVector.random2D());
  vv.add(PVector.random2D());
  vv.add(PVector.random2D());

  // not good
  for(var v : vv) {
    println(v);
  }

  // good
  vv.forEach(v -> {
    println(v);
  });
}
sampottinger commented 5 years ago

Hey there!

This fork moved us from a Java 5 to a Java 8 grammar which is why generics and lambdas work now. I think var was added in Java 10. So, it’s expected that the above snippet wont work but it doesn’t mean it’s desired.

Originally I was going to tackle moving to an 11 grammar in a separate PR as there’s some particularly meddlesome changes involved but ... we might still have some time on our hands ... so I’ll take a look again at moving the grammar to Java 11. Thanks!

sampottinger commented 5 years ago

Hey @hamoid! Thank you again for the bug report. The more I thought about it the more I realized that missing some of the new Java 11 features might be asking for some serious confusion (in particular, missing var is a bummer as more documentation online begins to adopt it). I have a working draft of this. I'll post shortly.

import java.util.*;
import java.util.function.*;

void setup() {
  List<String> list = new ArrayList<>();
  list.add("line1\nline2");
  list.add("line3");

  // Local variable type inference in loop
  for (var s : list) {
    println(s);
  }

  // Thanks https://codete.com/blog/java-8-java-11-quick-guide/
  IntFunction<Integer> testLambda = (var x) -> x * 2; // Type inference in lambda

  // Local variable type inference
  var testString = list.get(0);
  println(testString.lines().count()); // Java 11 API
}
sampottinger commented 5 years ago

105 is passing CI! I'll do a little more testing this afternoon and merge in this evening. Chat soon!

hamoid commented 5 years ago

Amazing! Thank you for doing this :)

sampottinger commented 5 years ago

The merge is in!