相关疑难解决方法(0)

为什么必须在scala中的for循环中为模式匹配定义过滤器?

要创建一个可以在Scala中用于理解的新类,似乎所有你需要做的就是定义一个map函数:

scala> class C[T](items: T*) {
     |   def map[U](f: (T) => U) = this.items.map(f)
     | }
defined class C

scala> for (x <- new C(1 -> 2, 3 -> 4)) yield x
res0: Seq[(Int, Int)] = ArrayBuffer((1,2), (3,4))
Run Code Online (Sandbox Code Playgroud)

但这仅适用于简单的for循环,其中左侧没有模式匹配<-.如果您尝试在那里进行模式匹配,则会收到filter未定义方法的投诉:

scala> for ((k, v) <- new C(1 -> 2, 3 -> 4)) yield k -> v
<console>:7: error: value filter is not a member of C[(Int, Int)]
       for ((k, v) <- new C(1 -> 2, 3 -> …
Run Code Online (Sandbox Code Playgroud)

for-loop scala map filter pattern-matching

18
推荐指数
2
解决办法
4721
查看次数

标签 统计

filter ×1

for-loop ×1

map ×1

pattern-matching ×1

scala ×1