How to hint at type inference when using static import?

I use junit with hamcrest in my unit tests, and I ran into a generic problem:


assertThat(collection, empty());

I know that type inference is not available in this way, and that one solution is to give a type hint, but how do I enter a hint when using static import?

+5
source share
2 answers

While type inference is not as powerful as we would like, in this case it really is the API that is to blame. He unreasonably restricts himself for no good reason. The is-empty connector works with any collection, not just collections of a specific one E.

, API

public class IsEmptyCollection implements Matcher<Collection<?>>
{
    public static Matcher<Collection<?>> empty()
    {
        return new IsEmptyCollection();
    }
}

assertThat(list, empty()) .

API.

@SuppressWarnings("unchecked")
public static Matcher<Collection<?>> my_empty()
{
    return (Matcher<Collection<?>>)IsEmptyCollection.empty();
}
+3

. :

/**
 * A matcher that returns true if the supplied {@link Iterable} is empty.
 */
public static Matcher<Iterable<?>> isEmpty() {
    return new TypeSafeMatcher<Iterable<?>>() {

        @Override
        public void describeTo(final Description description) {
            description.appendText("empty");
        }

        @Override
        public boolean matchesSafely(final Iterable<?> item) {
            return item != null && !item.iterator().hasNext();
        }
    };
}

:

List<String> list = new ArrayList<String>();
assertThat(list, isEmpty());

.

0

All Articles