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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With