What about PartialFunction.condOpt?
On Wed 12 Dec 2012 03:25:29 PM CET, Alois Cochard wrote:
> Hi folks,
>
> I write very often code like this:
>
> /def myFunction(x: Foo) = x.field match {/
> / case "a" => Some(Bar0(x))/
> / case "b" => Some(Bar1(x))/
> / case _ => None/
> /}/
>
>
> And this give me the feeling of repeating myself, so I wrote this
> little helper function:
>
> /def f[A, B](x: A)(f: PartialFunction[A, B]): Option[B] = if
> (f.isDefinedAt(x)) Some(f(x)) else None /
> /
> /
>
> So now I can write something like that:
>
> /def myFunction(x: Foo) = f(x.field)(_ match {/
> / case "a" => Some(Bar0(x))/
> / case "b" => Some(Bar1(x))/
> /})/
>
>
> This sounds quite basic, and useful to reduce boilerplate, but I
> wasn't able to find something like that in stdlib, am I missing
> something? would worth an addition or there is a better way?
>
> I tried using PartialFunction.lift ... but unfortunately I can't get
> it inferring type nicely so I end with less readable code.
>
> Cheers
>
> Alois Cochard
> /
> /
>
>
>