为什么不在Scala中设置方法来强制执行类似的类型?

时间:2015-11-27 11:16:13

标签: scala

考虑以下示例

val strings = Seq("foo", "bar")
val numbers = Seq(1,2,3)
strings.diff(numbers)

这是有效的代码(会产生一个空列表),但为什么scala不会认为我们正在比较不同类型的代码?

似乎为B >: Aintersectdiff定义了类型绑定union但不知何故它不会导致编译器拒绝我的示例为无效。< / p>

在scala中是否有类型严格/安全的方法来执行set操作?

2 个答案:

答案 0 :(得分:7)

因为Seqcovariant type(+A)

如果您希望diff使用stricted类型,可以通过以下方式试用:

strings.diff[String](numbers)

答案 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)