使用静态导入时如何提示类型推断?
我在单元测试中使用 junit 和 hamcrest,遇到了一个泛型问题:
assertThat(collection, empty());
我知道这种方式无法进行类型推断,解决方案之一是提供类型提示,但是在使用时我应该如何键入提示静态导入?
I am using junit with hamcrest in my unit tests and I came across a generics problem:
assertThat(collection, empty());
I am aware of type inference not being available this way and that one of the solutions is to give a type hint, but how should I type hint when using static imports?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
虽然类型推断并不像我们希望的那么强大,但在这种情况下,实际上是 API 出了问题。它无缘无故地限制自己。 is-empty 匹配器适用于任何集合,而不仅仅是特定
E
的集合。假设 API 是这样设计的
,那么
assertThat(list,empty())
按预期工作。你可以尝试说服作者更改API。同时你可以有一个包装纸
While type inference is not as powerful as we would like, in this case, it's really the API that's at fault. It unnecessarily restricts itself for no good reason. The is-empty matcher works on any collection, not just on collections of a specific
E
.Suppose the API is designed this way
then
assertThat(list, empty())
works as expected.You can try to convince the author to change the API. Meanwhile you can have a wrapper
我不太明白这个问题。这是我使用的方法:
我这样使用它:
这里泛型没有问题。
I don't quite understand the problem. Here's the method I use:
And I use it like this:
No problem with generics here.