I have large lists that I need to get the size of. Count returns an int, according to the scala api https://www.scala-lang.org/api/2.13.3/scala/collection/immutable/List.html, which may overflow on large lists.
How do I get around this?
CodePudding user response:
A solution could be:
aList.foldLeft(0L)((acc, _) => acc 1)
This will return the total number of elements as a Long number. If you want, you can wrap this functionality with the Pimp my library pattern:
implicit class LongList[A](list: List[A]) {
def sizeL: Long = list.foldLeft(0L)((acc, _) => acc 1)
}
As underlying in the comments, this operation will cost you O(n)
, so if you have other alternatives try to explore them :)