Scala:为什么 Seq.contains 采用 Any 参数,而不是序列类型的参数? [英] Scala: Why does Seq.contains take an Any argument, instead of an argument of the sequence type?
本文介绍了Scala:为什么 Seq.contains 采用 Any 参数,而不是序列类型的参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
例如,为什么 List(1,2,3,4).contains("wtf")
甚至可以编译?如果编译器拒绝这个不是很好吗?
So for example why does List(1,2,3,4).contains("wtf")
even compile? Wouldn't it be nice if the compiler rejected this?
推荐答案
很多有趣的答案,但这是我自己的理论:如果 contains
没有收到 Any
,那么 Seq
不能是协变的.
Lots of interesting answers, but here's my own theory: if contains
did not receive an Any
, then Seq
could not be co-variant.
参见,例如,Set
,它不是协变的,它的 contains
使用 A
而不是 Any代码>.
See, for instance, Set
, which is not co-variant and whose contains
take an A
instead of an Any
.
原因留给读者作为练习.;-) 但这里有一个提示:
The reasons for that is left as an exercise to the reader. ;-) But here is a hint:
scala> class Container[+A](elements: A*) {
| def contains(what: A): Boolean = elements exists (what ==)
| }
<console>:7: error: covariant type A occurs in contravariant position in type A of value what
def contains(what: A): Boolean = elements exists (what ==)
^
这篇关于Scala:为什么 Seq.contains 采用 Any 参数,而不是序列类型的参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文