-1

In Groovy, parentheses can be omitted when there is no ambiguity. However, the groovy compiler fails for this piece of code:

def firstChar(String str) { str[0] }

println " ".split(firstChar " ")

I have troubles understanding what is ambiguous here. The error is as follows:

Groovyc: Unexpected input: '"".split(firstChar " "'

In my actual use-case, the error reports completely unrelated element. For this code:

existingInputFile.withReader { reader ->
    def outputFile = new File(/name.txt/)
    outputFile.createNewFile()
    outputFile.withWriter { writer ->
        writer.write reader.lines()
                .map { line -> line.split " " }
                .map { line -> "${line.head()} ${line[1]}}" }
                .collect(Collectors.joining "\n")
    }
}

It complains about:

Groovyc: Unexpected input: '{'

pointing out to the very first line of the above snippet.

As you can see, I have a "nested" omitted parentheses in a method call in form of writer.write and Collectors.joining.

Is this a compiler bug or can something like that really be ambiguous?

Fureeish
  • 12,533
  • 4
  • 32
  • 62

1 Answers1

0

I would use a "standard" Groovy to fulfill your use-case:

// the slashy string should be used for regex only
new File('name.txt').withWriter { writer ->
    existingInputFile.splitEachLine( / / ){ __, first, second ->
        writer.write "$first $second\n" 
    }
}

without meddling with stream api and groovyc tricks.

injecteer
  • 20,038
  • 4
  • 45
  • 89
  • This is not an answer to my queston. This is a comment. – Fureeish Nov 08 '22 at 12:22
  • this is the answer to your actual use-case, and not what you trying to squese out groovy syntax – injecteer Nov 08 '22 at 15:47
  • I provided my actual use-case just for convenience. Im both the title and the actual question I ask specifically about the groovy compiler complaining about this specific usage of a given feature that, in my opinion, should work. I am not asking for code review or best practices. – Fureeish Nov 08 '22 at 19:54