Scala和dropWhile

时间:2016-10-21 13:36:12

标签: scala

我是HS的高级成员,也是函数式编程和Scala的新手。我在Scala REPL中尝试了一些构造,并需要一些返回响应的指导

//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)

1 个答案:

答案 0 :(得分:5)

Iterator.dropWhile只要与提供的谓词匹配就会删除任何值,并返回迭代器的其余部分:

  

跳过满足此迭代器的最长元素序列   给定谓词p,并返回剩余元素的迭代器。

您传递的提供的谓词表示第一个元素Double,因此它是您实现为List[A]的整个迭代器。

例如,如果您选择在isInstanceOf[Double]时放弃,则会收到包含单个元素1的列表:

scala> x.productIterator.dropWhile(_.isInstanceOf[Double]).toList
res13: List[Any] = List(1)
相关问题