[ 
https://issues.apache.org/jira/browse/GROOVY-10597?page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel&focusedCommentId=17527814#comment-17527814
 ] 

Eric Milles edited comment on GROOVY-10597 at 4/26/22 4:46 PM:
---------------------------------------------------------------

I tried a couple variations and there are multiple issues preventing a simple 
workaround:
{code:groovy}
String string() { '3.4' }
List<String> strings() {['3','4']}
@groovy.transform.CompileStatic
void test() {
  def x = ['2', *strings(), '5'] // infers as List<Object> -- should be fixed
  def y = ['2', string(), '5'] // infers as List<String>
  m(1, y as String[]) // works for x, y or inlined y but not inlined x
  m(1, y) // fails to match [int,List<String>] to [int,String...] so no good
  // " as String[]" may be replaced with ".toArray(new String[0])" or 
".toArray(String[]::new)"
}
void m(int i, String... strings) { }
{code}
So anyways, your original proposal of supporting spread to match variadic 
method seems quite sensible: {{m(1, '2', *strings(), '5')}}


was (Author: emilles):
Does STC let you spread into a list literal?  Like [‘w0’, *widgets(), ‘w3’] ?  
I’m not at my terminal to try it out. 

> Permit spread operator in static mode for varargs
> -------------------------------------------------
>
>                 Key: GROOVY-10597
>                 URL: https://issues.apache.org/jira/browse/GROOVY-10597
>             Project: Groovy
>          Issue Type: Improvement
>          Components: Static Type Checker
>    Affects Versions: 4.0.2
>            Reporter: Christopher Smith
>            Priority: Minor
>
> I have a varargs method that takes many parameters for inclusion into an 
> output JSON array. I am needing to preprocess some of these parameters, and I 
> tried to use the spread operator to deconstruct them inline. However, I'm 
> receiving the error "The spread operator cannot be used" because the compiler 
> can't determine arity.
> This is perfectly sensible, but in the specific case where the spread 
> operator would be applied in a position where its values expand into a 
> varargs, as long as the element type produced by the spread is a subtype of 
> the declared varargs type, it would be helpful for the spread to succeed.
> Sample:
> {code:groovy}
> @CompileStatic
> class Groovy10597 {
>   static void output(int code, String... widgets) {
>     println "$code: ${Arrays.toString(widgets)}"
>   }
>   static List<String> createWidgets() {
>     ['w1', 'w2']
>   }
>   static void sample() {
>     output(42, 'w0', *createWidgets(), 'w3')
>   } 
> }
> {code}



--
This message was sent by Atlassian Jira
(v8.20.7#820007)

Reply via email to