Assignment->lambda->statement fails with "statement enter $[ followed by statement enter $["
fejesjoco opened this issue · comments
fejesjoco commented
Repro sample:
public static void main(String[] args) {
CodeBlock inner =
CodeBlock.builder()
.beginControlFlow("() ->")
.addStatement("return 42")
.endControlFlow()
.build();
System.err.println("<<<" + inner + ">>>");
CodeBlock outer1 =
CodeBlock.builder()
.add(
"$T lambda = $L;",
ParameterizedTypeName.get(
ClassName.get(Supplier.class), ClassName.get(Integer.class)),
inner)
.build();
System.err.println("<<<" + outer1 + ">>>");
CodeBlock outer2 =
CodeBlock.builder()
.addStatement(
"$T lambda = $L",
ParameterizedTypeName.get(
ClassName.get(Supplier.class), ClassName.get(Integer.class)),
inner)
.build();
System.err.println("<<<" + outer2 + ">>>");
}
The first two prints work, the third fails:
<<<() -> {
return 42;
}
>>>
<<<java.util.function.Supplier<java.lang.Integer> lambda = () -> {
return 42;
}
;>>>
Exception in thread "main" java.lang.IllegalStateException: statement enter $[ followed by statement enter $[
at com.squareup.javapoet.Util.checkState(Util.java:62)
at com.squareup.javapoet.CodeWriter.emit(CodeWriter.java:284)
at com.squareup.javapoet.CodeWriter.emit(CodeWriter.java:229)
at com.squareup.javapoet.CodeWriter.emitLiteral(CodeWriter.java:365)
at com.squareup.javapoet.CodeWriter.emit(CodeWriter.java:240)
at com.squareup.javapoet.CodeWriter.emit(CodeWriter.java:229)
at com.squareup.javapoet.CodeBlock.toString(CodeBlock.java:97)
at java.base/java.lang.String.valueOf(String.java:2958)
I think this should work, because the assignment is a statement, and because of the lambda syntax the rvalue can also contain statements. But it seems like Javapoet is confused by statements within each other.
CoderStory commented
.addStatement(
"$T lambda = $L",
ParameterizedTypeName.get(
ClassName.get(Supplier.class), ClassName.get(Integer.class)),
inner**.toString()**)
WangXiequn commented
#884 I try to do it in this pull request.