考虑以下示例
val strings = Seq("foo", "bar")
val numbers = Seq(1,2,3)
strings.diff(numbers)
这是有效的代码(会产生一个空列表),但为什么scala不会认为我们正在比较不同类型的代码?
似乎为B >: A
,intersect
和diff
定义了类型绑定union
但不知何故它不会导致编译器拒绝我的示例为无效。< / p>
在scala中是否有类型严格/安全的方法来执行set操作?
答案 0 :(得分:7)
答案 1 :(得分:4)
即使我很欣赏chengpohi的回答,也需要额外的打字/思考,所以我现在使用严格的版本(继续我的问题中的例子):
implicit class StrictSetOps[T](someSeq: Seq[T]) {
def strictDiff(that: Seq[T]) = {
someSeq.diff(that)
}
def strictUnion(that: Seq[T]) = {
someSeq.union(that)
}
def strictIntersect(that: Seq[T]) = {
someSeq.intersect(that)
}
}
// rejected by compiler
strings.strictDiff(numbers)
// compiler and the lazy developer are happy
val otherStrings = Seq("foo", "bar")
strings.strictDiff(otherStrings)