Java “The blank final field may not have been initialized” Anonymous Interface vs Lambda Expression

前端 未结 4 2130
余生分开走
余生分开走 2020-12-06 15:49

I\'ve recently been encountering the error message \"The blank final field obj may not have been initialized\".

Usually this is the case if you try to refer to a field t

4条回答
  •  情书的邮戳
    2020-12-06 16:50

    You can bypass the problem by

            Runnable run = () -> {
                (this).obj.toString(); 
            };
    

    This was discussed during lambda development, basically the lambda body is treated as local code during definite assignment analysis.

    Quoting Dan Smith, spec tzar, https://bugs.openjdk.java.net/browse/JDK-8024809

    The rules carve out two exceptions: ... ii) a use from inside of an anonymous class is okay. There is no exception for a use inside of a lambda expression

    Frankly I and some other people thought the decision is wrong. The lambda only captures this, not obj. This case should have been treated the same as anonymous class. The current behavior is problematic for many legit use cases . Well, you can always bypass it using the trick above- fortunately definite assignment analysis is not too smart and we can fool it.

提交回复
热议问题