【发布时间】:2011-05-21 19:37:26
【问题描述】:
要创建一个可在 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))
但这仅适用于 <- 左侧没有模式匹配的简单 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 -> 4)) yield k -> v
为什么这里需要过滤器来实现模式匹配?我原以为 Scala 只会将上述循环转换为等效的 map 调用:
scala> new C(1 -> 2, 3 -> 4).map{case (k, v) => k -> v}
res2: Seq[(Int, Int)] = ArrayBuffer((1,2), (3,4))
但这似乎可以正常工作,因此必须将 for 循环转换为其他内容。翻译成什么需要filter方法?
【问题讨论】:
标签: scala filter map for-loop pattern-matching