Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 981
Mequrel Avatar asked Mar 25 '14 10:03

Mequrel


1 Answers

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")
like image 188
Jean-Philippe Pellet Avatar answered Oct 15 '22 11:10

Jean-Philippe Pellet