我无法理解 immutable.Map.transform 和 immutable.Map.map 之间的差异/原因。看起来转换不会改变键,但这似乎只是映射方法的一个微不足道的变体。我错过了什么吗?
我期望找到一种方法,当/如果访问该元素时,将函数应用于映射的(键,值)(而不是必须使用映射函数急切地迭代映射)。有这样的方法吗?
最佳答案
您可以使用mapValues
来做到这一点。以下是文档中的解释:
def mapValues[C](f: (B) ⇒ C): Map[A, C]
Transforms this map by applying a function to every retrieved value.
f - the function used to transform values of this map.
returns - a map view which maps every key of this map to f(this(key)). The resulting map wraps the original map without copying any elements.
编辑:
虽然扩展集合 API 的类通常不是一个好主意,但它可以像这样工作:
class LazilyModifiedMap[A,B,C](underlying: Map[A,B])(f: (A,B) => C) extends Map[A,C] {
def get(key: A) = underlying.get(key).map( x => f(key, x))
def iterator = underlying.iterator.map { case (k,v) => (k, f(k,v)) }
def -(key: A) = iterator.toMap - key
def +[C1 >: C](kv: (A,C1)) = iterator.toMap + kv
}
关于api - 为什么scala中同时使用transform和map方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16737165/