Modifying local variable from inside lambda

后端 未结 11 1227
失恋的感觉
失恋的感觉 2020-11-28 04:30

Modifying a local variable in forEach gives a compile error:

Normal

    int ordinal = 0;
    for (Example s : list) {
          


        
11条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-28 04:53

    To have a more general solution, you can write a generic Wrapper class:

    public static class Wrapper {
        public T obj;
        public Wrapper(T obj) { this.obj = obj; }
    }
    ...
    Wrapper w = new Wrapper<>(0);
    this.forEach(s -> {
        s.setOrdinal(w.obj);
        w.obj++;
    });
    

    (this is a variant of the solution given by Almir Campos).

    In the specific case this is not a good solution, as Integer is worse than int for your purpose, anyway this solution is more general I think.

提交回复
热议问题