Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scala iterator hasNext random behaviour

Tags:

scala

var intList = Iterator(range(1,10))
println("data"+intList)
println(intList.hasNext)

Last line gives True, whereas for

var intList = Iterator(range(1,10))
println("data"+intList.toList)
println(intList.hasNext)

Last line give False

Why even if intList is immutable I am not assigning it to any new variable.

like image 223
SushantPatade Avatar asked Apr 01 '26 15:04

SushantPatade


1 Answers

You're right that lists are immutable in Scala. However, your intList is not a list; it's an Iterator, which uses next() to iterate and is mutable.

println("data " + intList)

This prints out a representation of the iterator. It probably says something like "non-empty iterator". All it needs to do is call hasNext, which changes nothing.

println("data " + intList.toList)

toList is a method (don't let the lack of parentheses fool you; everything you call on an object is a method in Scala), and exhausts the iterator, which means it calls next() until there's nothing left. Then your iterator is empty, so hasNext rightly tells you that there is no next value.

like image 97
Silvio Mayolo Avatar answered Apr 04 '26 08:04

Silvio Mayolo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!