[lvti][leftovers] lvti + leftovers

Remi Forax forax at univ-mlv.fr
Fri Apr 14 18:29:01 UTC 2017


I've just played a little with the '_', the new scope rule in a lambda and 'var'.

First, after cloning amber/amber, i've stupidly spent 10 mins wondering why nothing was working until i remarked that the development was done in different branches.
I've merged leftovers and lvti, to be able to write the following example*:

  @SafeVarargs
  private static <T> Map<T, List<Integer>> positions(T... array) {
    var map = new HashMap<T, List<Integer>>();
    for(var i = 0; i < array.length; i++) {
      var element = array[i];
      map.computeIfAbsent(element, element -> new ArrayList<>())
         .add(i);
    }
    return map;
  }

  public static void main(String[] _) {
    var map = positions("foo", "bar", "foo");
    System.out.println(map.getOrDefault("foo", List.of()));
  }

The wunderbar '_' allows to write yet another signature of the main,
You have also the morse version:
  public static void main(String..._)
(yes the space is not required)

The call map.computeIfAbsent(element, element -> ...) is now supported !
Note that, in this case, map.computeIfAbsent(element, _ -> ...) also works.

Another example, with yet another Logger:
  import java.lang.System.Logger.Level;
  import static java.lang.System.Logger.Level.*;
  import java.util.function.Function;
  import java.util.function.Predicate;

  public interface Log {
    public static Log logger(Class<?> type) {
      var logger = System.getLogger(type.getName());
      return (level, value, message) -> logger.log(level, message.apply(value));
    }

    public void log(Level level, Object value, Function<Object, Object> message);

    public default Log filter(Predicate<? super Level> filter) {
      return (level, value, message) -> { if (filter.test(level)) log(level, value, message); };
    }

    public static void main(String[] _) {
      var logger = Log.logger(Log.class)
                      .filter(level -> WARNING.getSeverity() <= level.getSeverity());
      logger.log(ERROR, "test1", result -> result);
      logger.log(DEBUG, "test2", result -> result);

      String result = "hello";
      logger.log(ERROR, result, result -> result + " world");
    }
  }

the main() compiles, even if everything is a result :)
As a game, try to predict what are the errors raised by javac 9 in the body of the main.

cheers,
Rémi

* and yes, you can write it with a Collector, in less lines ...


More information about the amber-dev mailing list