为什么Scala Set上没有lengthCompare方法?

Jac*_*cob 8 scala

在Scala中Seq,有一种lengthCompare方法可以返回Seq长度与给定之间的比较Int而不计算长度Seq.

它在特征SeqLike中实现如下:

/** Compares the length of this $coll to a test value.
   *
   *   @param   len   the test value that gets compared with the length.
   *   @return  A value `x` where
   *   {{{
   *        x <  0       if this.length <  len
   *        x == 0       if this.length == len
   *        x >  0       if this.length >  len
   *   }}}
   *  The method as implemented here does not call `length` directly; its running time
   *  is `O(length min len)` instead of `O(length)`. The method should be overwritten
   *  if computing `length` is cheap.
   */
  def lengthCompare(len: Int): Int = {
    if (len < 0) 1
    else {
      var i = 0
      val it = iterator
      while (it.hasNext) {
        if (i == len) return if (it.hasNext) 1 else 0
        it.next()
        i += 1
      }
      i - len
    }
  }
Run Code Online (Sandbox Code Playgroud)

由于这个实现只需要一个iterator,为什么不定义IterableLike

这将使它在使用Seq,Set并且Map集合.

Hen*_*rik 1

昨天刚刚发布的经过大幅修改的新 Scala 2.13 系列中有一个,请参见此处。原因很简单,Scala 集合的很多问题都没有按照应有的方式进行,现在已经得到修复。它存在于新版本中的事实表明,之前排除它并不是一个积极的选择。