Skip to content
This repository has been archived by the owner on Oct 10, 2024. It is now read-only.

MethodSpec.beginControlFlow inserts unneccessary space when argument is empty #795

Open
DanielGronau opened this issue Jul 13, 2020 · 6 comments

Comments

@DanielGronau
Copy link

I want to write code like this:

public void test() {
   {
     int value = 42;
     someCode(value, 5, value);
   }
   {
     int value = 23;
     someCode(value, 7, value);
   }
}

To generate the code blocks, I use

...
.beginControlFlow("");
.addStatement("int value = 42")
.addStatement("someCode(value, 5, value)")
.endControlFlow();
...

This works almost as expected, but the curly braces don't line up. Would it be possible to remove the extra space when beginControlFlow gets an empty argument?

@Egorand
Copy link
Collaborator

Egorand commented Jul 13, 2020

Sounds like a legit use case. I'd actually suggest adding a no-arg beginControlFlow() overload in addition to fixing the behavior for the empty string case. Wanna submit a PR?

@JakeWharton
Copy link
Collaborator

I'm not sure this is control flow though. You could build the block contents in a CodeBlock and then add it to the enclosing method with addCode("{$>\n$L\n$<}\n", block).

@DanielGronau
Copy link
Author

@JakeWharton I think this would be a quite theoretical distinction. Is this a control flow then?

if(true) {
    System.out.println("hey");
}

@JakeWharton
Copy link
Collaborator

As far as JavaPoet is concerned yes. The library does not care what the semantic meaning your code has, we merely care about its syntactical form.

@hariohmprasath
Copy link

Hi, I have created a PR for this issue, please review and let me know if it looks good for merge:
https://github.com/square/javapoet/pull/796

jdyjjj added a commit to jdyjjj/javapoet that referenced this issue Apr 20, 2022
@jdyjjj
Copy link

jdyjjj commented Apr 20, 2022

I added a no-arg beginControlFlow() overload in addition to fixing the behavior for the empty string case.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants