在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集合.
| 归档时间: |
|
| 查看次数: |
606 次 |
| 最近记录: |