简体   繁体   中英

How can I convert scala Map to a partial function

Currently I use the following snippet of code:

private val aMap = Map(
  "J" -> Journey,
  "T" -> Training
)

def partialFunction = {
  case x if aMap isDefinedAt x => aMap(x)
}

It seems to me that Maps naturally should define a partial function. Does Scala have any standard/more concise and explicit way to convert a map to a partial function? Maybe some kind of an implicit conversion?

A Scala Map actually is a PartialFunction ; you can just use it as such. No conversion required, implicit or explicit.

For instance:

val pf: PartialFunction[Int, String] = Map(1 -> "one")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM