Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Empty partial function in Scala

It seems to me like the { case ... => ... } syntax for partial functions require at least one case:

scala> val pf: PartialFunction[String, String] = { case "a" => "b" }  pf: PartialFunction[String,String] = <function1>  scala> val pf: PartialFunction[String, String] = { }                 <console>:5: error: type mismatch;  found   : Unit  required: PartialFunction[String,String]        val pf: PartialFunction[String, String] = { }                                                  ^ 

So, what's the best way to define an "empty" partial function? Is there a better way than "manually" overriding isDefinedAt and apply?

like image 237
aioobe Avatar asked Aug 25 '11 10:08

aioobe


People also ask

What is partial function in Scala?

When a function is not able to produce a return for every single variable input data given to it then that function is termed as Partial function. It can determine an output for a subset of some practicable inputs only. It can only be applied partially to the stated inputs.

What is andThen in Scala?

andThen is just function composition. Given a function f val f: String => Int = s => s.length. andThen creates a new function which applies f followed by the argument function val g: Int => Int = i => i * 2 val h = f.andThen(g) h(x) is then g(f(x))


2 Answers

Map is a PartialFunction so you can do:

val undefined: PartialFunction[Any, Nothing] = Map.empty 
like image 120
mpilquist Avatar answered Sep 17 '22 13:09

mpilquist


Since Scala 2.10 you can use:

val emptyPf = PartialFunction.empty[String, String] 
like image 26
Andrejs Avatar answered Sep 17 '22 13:09

Andrejs