Scala - iterators and takeWhile

I am running the following piece of code:

 val it = List(1,1,1,2,2,3,3).iterator.buffered
 val compare = it.head
it.takeWhile(_ == compare).toList

and it returns (1,1,1). However, if I run this as:

val it = List(1,1,1,2,2,3,3).iterator.buffered
it.takeWhile(_ == it.head).toList

I am getting (1,1). Why is this the case? Isn't head evaluated upon calling takeWhile and the result should be the same?


Because the iterator is mutable, the value of it.head depends on when it is evaluated.

Inspecting the implementation of takeWhile reveals that it removes the head of the iterator before applying the predicate.

So, on the third iteration, it.head evaluated from within the predicate will be 2, because the third element has already been removed.

This is an illustration of why you should prefer immutability. It rules out a whole class of non-obvious behaviour like this.

Need Your Help

Lambda expression example with System.Action<T> for a MEF case?

.net-3.5 lambda mef

I am new to System.Action&lt;T&gt; and Lambda expression. Here is one case I would like to use.

Hiding the soft keyboard in MonoDroid

android monodroid android-softkeyboard

I've got an Activity with a bunch of EditTexts and a button. When the user clicks the button, an answer based on the input from the EditTexts appears in the caption of the button. In the buttonclick

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.