hamcrest-compose icon indicating copy to clipboard operation
hamcrest-compose copied to clipboard

hasFeature allows incompatible matcher type for feature type

Open markhobson opened this issue 10 years ago • 1 comments
trafficstars

The following statement compiles:

hasFeature(Objects::toString, equalTo(1));

Looking at the current factory method signature:

<T, U> Matcher<T> hasFeature(Function<T, U> featureFunction, Matcher<? super U> featureMatcher)

We can see that U is being inferred as Object which is the common supertype of String and Integer. This is explained by Why doesn't type argument inference fail when I provide inconsistent method arguments? and is due to Java 8's Generalized Target-Type Inference.

To raise a compilation error requires explicit type parameters:

hasFeature((Function<Object, String>) Objects::toString, equalTo(1)); // error
ComposeMatchers.<Object, String>hasFeature(Objects::toString, equalTo(1)); // error

But this is unwieldy.

markhobson avatar May 24 '15 13:05 markhobson

Note that this a general problem with Java 8 generics and is applicable to Hamcrest itself. For example:

assertThat(singletonList("x"), contains(1)); // error under Java 7 but not Java 8

markhobson avatar May 24 '15 14:05 markhobson