Reputation: 12258
tl;dr; It's because of infix operators, nothing to do with extractors
I've been playing around with extractors in scala and found the fact that both the cases below are valid syntax a bit puzzling?! What's the story?
class Foo(val items:List[String], val number:Int)
object FooEnough {
def unapply(f:Foo):Option[(List[String], Int)] = if(f.number > 2) Some(f.items, f.number) else None
}
val foo = new Foo("a" :: "b" :: "c" :: Nil, 3)
val matches:String = foo match {
case FooEnough("a" :: "b" :: "c" :: Nil, 3) => "first case"
case "a" :: "b" :: "c" :: Nil FooEnough 4 => "second case"
}
//matches == "first case"
If I create another extractor, which extracts 3 parameters, how am I meant to call this using the syntax as in the 2nd case above?
object FooSpectrum {
def unapply(f:Foo):Option[(String, List[String], Int)] =
if(f.number > 2) Some("zx", f.items, f.number) else None
}
foo match {
case FooSpectrum("zx", "a" :: "b" :: "c" :: Nil, 3) => "first case" //compiles
case "zx" FooSpectrum "a" :: "b" :: "c" :: Nil 4 => "second case" //doesn't compile
}
Upvotes: 2
Views: 279
Reputation: 24423
This is because of the infix operator magic scala provides. You can also write String Map Int
instead of Map[String,Int]
. This only works for binary types/functions, because it would make no sense for more than 2 args and would also be hard to parse.
Upvotes: 4