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?
Map("" -> "") match { case Params.Foo(value) => 5 }with yourobject Params extends Dynamicthe compiler melts down with aNullPointerException- definitely looks like a bug to me.NullpointerExceptionthat is in my way.matchblock; resorting to Dynamic here looks like a bad idea and in my opinion leads to unreadable non-Scalaesque code whichDynamicwas not meant for.Params.Fooas nested objects all the time. I don't see how that is 'unreadable', and 'non-Scalaesque'. Unfiltered uses it all the time, also for extracting parameters, so I don't see why you shouldn't try to make the syntax a little less verbose and clunky. Also the ScalaDocs don't mention anything on whatDynamicwas meant for, other than a pretty generic description that perfectly matches my use case.