Generics hell: hamcrest matcher as a method parameter

僤鯓⒐⒋嵵緔 提交于 2019-12-03 10:13:21

However, I believe a matcher that accepts an Iterable of objects should be accepted by the matchIt() method as well

No, that is not correct. Instead of Iterable, let's consider List for the moment. So you have a Matcher<List<Object>>, and its matches method takes a List<Object>. Now, would this take a List<String>? No. And you probably already know why -- because it could add an object of type Object into the list.

Now, I know that in naming the class Matcher, you expect the matches method to be read-only, and not mutate the list given to it. However, there is no guarantee of that. If indeed it does not add anything to the list, the correct type for the matcher would be Matcher<List<?>>, which (1) does not allow the matches method to add anything to the list except null, and (2) will allow the matches method to take a list of any type.

I believe that your current method signature public boolean matchIt(final Matcher<? super List<String>> matcher) already allows Matcher<List<?>> (or Matcher<Iterable<?>>).

Anything wrong with this?

public boolean matchIt(final Matcher<? extends Iterable<String>> matcher);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!