One of the things I don't like about extractors is that they cannot have parameters. So I cannot have extractors like Param
in:
req match { case Param("foo")(foo) => … }
Dynamic Extractors?
That's unfortunate, and I hope it will change some day, but then this morning I figured I could fix it by using the Dynamic trait.
object Params extends Dynamic {
def selectDynamic(name: String) = new {
def unapply(params: Map[String, String]): Option[String] = params.get(name)
}
}
… hoping that would allow me use Params in a pattern matching statement like this:
req match { case Params.Foo(value) =>
// matching Map("Foo" -> "Bar"), extracting "Bar" in value
It doesn't work
… but it doesn't work. It seems the compiler is still getting confused.
scala> Map("Foo" -> "bar") match { case Params.Foo(value) => value }
<console>:10: error: value applyDynamic is not a member of object Params
error after rewriting to Params.<applyDynamic: error>("Foo")
possible cause: maybe a wrong Dynamic method signature?
Map("Foo" -> "bar") match { case Params.Foo(value) => value }
^
<console>:10: error: not found: value value
Map("Foo" -> "bar") match { case Params.Foo(value) => value }
^
Which I find surprising, since
object Params {
object Foo {
def unapply{params: Map[String, String]): Option[String] = …
}
}
would work fine. Also, if I assign Params.Foo
to a variable first, everything is okay:
scala> val Foo = Params.Foo
Foo: AnyRef{def unapply(params: Map[String,String]): Option[String]} = Params$$anon$1@f2106d8
scala> Map("Foo" -> "bar") match { case Foo(value) => value }
warning: there were 1 feature warning(s); re-run with -feature for details
res2: String = bar
Should this be considered a bug?