KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
Below is the source for the reduceLeft method of Scala's TraversableOnce trait. What is happening with the line that reads var acc: B = 0.asInstanceOf[B] ? To me, it seems that if I call this on a list of Strings, such as List("a", "b", "c") , this would result in something like 0.asInstanceOf[String] . However, 0.asInstanceOf[String] throws a ClassCastException at run time if I try it directly. What is happening with that line, and why is it different than calling 0.asInstanceOf[String] directly when called on a list of Strings? def reduceLeft[B >: A](op: (B, A) => B): B = { if (isEmpty) throw new UnsupportedOperationException("empty.reduceLeft") var first = true var acc: B = 0.asInstanceOf[B] for (x <- self) { if (first) { acc = x first = false } else acc = op(acc, x) } acc } Bonus question: why is acc even initialized to that value? It looks like the code in the first iteration of the for loop will just overwrite that value with the first element in the TraversableOnce object.
Tags (comma-separated)
Save Edits
Cancel