1

Please check the sample JUnit class below:

import groovy.transform.CompileStatic
import org.apache.commons.lang3.tuple.Pair
import org.junit.Test
import java.util.function.Function

@CompileStatic
class GroovyFunctionTypeInferenceTest {
  @Test
  void functionWithoutPairTest() {
    // some function that operates on list and returns an element of this list
    Function<List<String>, String> function =
        { List<Pair<String, Integer>> it -> it[0] } as Function
    def list = new ArrayList<String>()
    function.apply(list)
  }

  @Test
  void functionWithPair1Test() {
    // some function that operates on list and returns an element of this list
    Function<List<Pair>, Pair> function =
        { List<Pair<String, Integer>> it -> it[0] } as Function
    def list = new ArrayList<Pair>()
    function.apply(list)
  }

  @Test
  void functionWithPair2Test() {
    // some function that operates on list and returns an element of this list
    Function<List<Pair<String, Integer>>, Pair<String, Integer>> function =
        { List<Pair<String, Integer>> it -> it[0] } as Function
    def list = new ArrayList<Pair<String,Integer>>()
    function.apply(list)
  }
}

Functions functionWithoutPairTest and functionWithPair1Test compile successfully, but functionWithPair2Test fails with the following errors:

Error:(36, -1) Groovy-Eclipse: Groovy:[Static type checking] - Incompatible generic argument types. Cannot assign java.util.function.Function <java.util.List, org.apache.commons.lang3.tuple.Pair> to: java.util.function.Function <List, Pair>
Error:(38, -1) Groovy-Eclipse: Groovy:[Static type checking] - Cannot call java.util.function.Function <java.util.List, org.apache.commons.lang3.tuple.Pair>#apply(java.util.List <Pair>) with arguments [java.util.ArrayList <Pair>]

It looks like groovy does not like nested generics. Dynamic compilation is not an option in my case and strict type checking is a hard requirement.

Does anyone encounter similar error and has an advice?

Michal Wilkowski
  • 727
  • 5
  • 14
  • Isn't the the param in the closure of the first function wrong (List vs List)? – cfrick Feb 23 '17 at 19:36
  • That is interesting. When I look at it - yes, it looks wrong. However, this function actually compiles :-). The function that does not compile is functionWithPair2Test and this one does not have any mistake. Anyway, the question is not valid anymore - I checked Groovy JIRA and there is already an open ticket for this. So it is known bug and it is a matter of time when they fix it. – Michal Wilkowski Mar 05 '17 at 21:49
  • Then please add this as an answer or at least provide an id/link here in a comment for the sake of others, that might find this question on their search for this or a similar problem. – cfrick Mar 06 '17 at 06:08
  • https://issues.apache.org/jira/browse/GROOVY-7985 – Michal Wilkowski Mar 10 '17 at 22:25

0 Answers0