Java: Assign a variable within lambda

前端 未结 4 1920
忘了有多久
忘了有多久 2021-02-08 03:22

I cannot do this in Java:

Optional optStr = Optional.of(\"foo\");
String result;
optStr.ifPresent(s -> result = s);

The doc sa

4条回答
  •  野的像风
    2021-02-08 03:47

    Another way, similar to what Tunaki has written, is to use a single-cell table:

    Optional optStr = Optional.of("foo");
    String[] temp = new String[1];
    optStr.ifPresent(s -> temp[0] = s);
    String result = temp[0];
    

    The table object is final, what changes is its content.

    Edit: A word of warning though - before using this hacky solution check out the other answers to OP's question, pointing out why it's a bad idea to use this workaround and consider if it's really worth it!

提交回复
热议问题