Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

hasFeature allows incompatible matcher type for feature type #2

Open
markhobson opened this issue May 24, 2015 · 1 comment
Open

hasFeature allows incompatible matcher type for feature type #2

markhobson opened this issue May 24, 2015 · 1 comment

Comments

@markhobson
Copy link
Owner

markhobson commented May 24, 2015

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
Copy link
Owner Author

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

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

No branches or pull requests

1 participant