Scala - What is the difference between size and length of a Seq?
What is the difference between size and length of a Seq? When to use one and when the other?
scala> var a :Seq[String] = Seq("one", "two")
a: Seq[String] = List(one, two)
scala> a.size
res6: Int = 2
scala> a.length
res7: Int = 2
It's the same?
Thanks
Nothing. In the Seq doc, at the size method it is clearly stated: "The size of this sequence, equivalent to length
.".
size
is defined in GenTraversableOnce
, whereas length
is defined in GenSeqLike
, so length
only exists for Seq
s, whereas size
exists for all Traversable
s. For Seq
s, however, as was already pointed out, size
simply delegates to length
(which probably means that, after inlining, you will get identical bytecode).
In a Seq they are the same, as others have mentioned. However, for information, this is what IntelliJ warns on a scala.Array
:
Replace .size with .length on arrays and strings
Inspection info: This inspection reports array.size and string.size calls. While such calls are legitimate, they require an additional implicit conversion to SeqLike to be made. A common use case would be calling length on arrays and strings may provide significant advantages.
Nothing, one delegates to the other. See SeqLike trait.
/** The size of this $coll, equivalent to `length`.
*
* $willNotTerminateInf
*/
override def size = length