Matching with custom combinations/operators

前端 未结 3 647
我在风中等你
我在风中等你 2021-01-12 20:29

I know that you can do matching on lists in a way like

val list = List(1,2,3)
list match {
  case head::tail => head
  case _ => //whatever
}
         


        
3条回答
  •  忘掉有多难
    2021-01-12 20:50

    Matching with case head :: tail uses an infix operation pattern of the form p1 op p2 which gets translated to op(p1, p2) before doing the actual matching. (See API for ::)

    The problem with + is the following:

    While it is easy to add an

    object + { 
      def unapply(value: Int): Option[(Int, Int)] = // ...
    }
    

    object which would do the matching, you may only supply one result per value. E.g.

    object + { 
      def unapply(value: Int): Option[(Int, Int)] = value match {
        case 0 => Some(0, 0)
        case 4 => Some(3, 1)
        case _ => None
    }
    

    Now this works:

    0 match { case x + 0 => x } // returns 0
    

    also this

    4 match { case x + 1 => x } // returns 3
    

    But this won’t and you cannot change it:

    4 match { case x + 2 => x } // does not match
    

    No problem for ::, though, because it is always defined what is head and what is tail of a list.

提交回复
热议问题