有没有办法定义一个 Map,其中 Map 值取决于它的键,比如
Map(key -> f(key), key2 -> f(key2), ...).
最佳答案
你看错了...
一个 Map[K,V]
也是 Partialfunction[K,V]
的一个实例.因此,在您使用 Map
的任何地方进行更改类型(vals、方法参数等)为 PartialFunction
.
然后你就可以使用 f
直接,或提供 Map[K,V]
作为您在键和值之间没有简单代数关系的实例。
例如
def methodUsingMapping(x: PartialFunction[Int,Boolean]) = ...
//then
val myMap = Map(1->true, 2->true, 3->false)
methodUsingMapping(myMap)
//or
val isEven = PartialFunction(n: Int => n % 2 == 0)
methodUsingMapping(isEven)
//or
//note: case statements in a block is the smart way
// to define a partial function
// In this version, the result isn't even defined for odd numbers
val isEven: PartialFunction[Int,Boolean] = {
case n: Int if n % 2 == 0 => true
}
methodUsingMapping(isEven)
您可能还想考虑使用
(K) => Option[V]
,在这种情况下,您可以通过 lift
提供该类型的实例方法,映射继承自 PartialFunction
例如
def methodUsingMapping(x: (Int)=>Option[Boolean]) = ...
//then
val myMap = Map(1->true, 2->true, 3->false)
methodUsingMapping(myMap.lift)
//or
def isEven(n: Int) = Some(n % 2 == 0)
methodUsingMapping(isEven)
//or
def isEven(n: Int) = n % 2 == 0
methodUsingMapping(x => Some(isEven(x)))
关于Scala - 如何定义映射,其中值取决于键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28583594/