Explain this pattern matching code

前端 未结 3 536
没有蜡笔的小新
没有蜡笔的小新 2020-12-25 14:27

This code is from Querying a Dataset with Scala\'s Pattern Matching:

object & { def unapply[A](a: A) = Some((a, a)) }

\"Julie\" match {
  case          


        
3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-25 14:36

    Here's how unapply works in general:

    When you do

    obj match {case Pattern(foo, bar) => ... }
    

    Pattern.unapply(obj) is called. This can either return None in which case the pattern match is a failure, or Some(x,y) in which case foo and bar are bound to x and y.

    If instead of Pattern(foo, bar) you did Pattern(OtherPattern, YetAnotherPatter) then x would be matched against the pattern OtherPattern and y would be matched against YetAnotherPattern. If all of those pattern matches are successful, the body of the match executes, otherwise the next pattern is tried.

    when the name of a pattern is not alphanumeric, but a symbol (like &), it is used infix, i.e. you write foo & bar instead of &(foo, bar).


    So here & is a pattern that always returns Some(a,a) no matter what a is. So & always matches and binds the matched object to its two operands. In code that means that

    obj match {case x & y => ...}
    

    will always match and both x and y will have the same value as obj.

    In the example above this is used to apply two different patterns to the same object.

    I.e. when you do

    obj match { case SomePattern & SomeOtherPattern => ...}`
    

    first the pattern & is applied. As I said, it always matches and binds obj to its LHS and its RHS. So then SomePattern is applied to &'s LHS (which is the same as obj) and SomeOtherPattern is applied to &'s RHS (which is also the same as obj).

    So in effect, you just applied two patterns to the same object.

提交回复
热议问题