Priyanka  Dangi Priyanka Dangi - 4 years ago 245
Scala Question

Scala and dropWhile

I'm a senior in HS and a newbie to functional programming and Scala. I was trying out a few constructs in Scala REPL and needed some guidance for the return responses

//Defined a tuple

scala> val x =(2.0, 3.0, 1)
x: (Double, Double, Int) = (2.0,3.0,1)

//This made sense to me. Result is a list of values that are of type Ints
scala> x.productIterator.dropWhile(_.isInstanceOf[Double]).toList
res1: List[Any] = List(1)

**//This DID NOT make sense to me. Why are Double values included?**
scala> x.productIterator.dropWhile(_.isInstanceOf[Int]).toList
res0: List[Any] = List(2.0, 3.0, 1)

//filter operator seems to work
scala> x.productIterator.toList.filter(x => x.isInstanceOf[Double])
res7: List[Any] = List(2.0, 3.0)

Answer Source

Iterator.dropWhile will drop any value as long as it matches the provided predicate, and return the remainder of the iterator:

Skips longest sequence of elements of this iterator which satisfy given predicate p, and returns an iterator of the remaining elements.

The provided predicate you passed fails for the first element, which is of type Double, hence it the entire iterator which you materialize to a List[A].

If, for example, you chose to drop while isInstanceOf[Double], you'd receive a list with a single element 1:

scala> x.productIterator.dropWhile(_.isInstanceOf[Double]).toList
res13: List[Any] = List(1)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download