0

I have a question regarding the following portion of code:

sealed trait Claim { val claimId: Int }
case class Full(val claimId: Int) extends Claim
case class Partial(val claimId: Int, percentage: Double) extends Claim
case class Generic(override val claimId: Int) extends Claim

case class Location(stateCode: Option[String], zipCode: Option[String])
case class Req(productId: String, location: Location, claim: Claim)

object PricingSystem {
  type PC = Tuple2[Req, Option[Double]]  

  def handleFullClaim: PartialFunction[PC, PC] = { 
    case (c@Req(id, l, Full(claimId)), basePrice)  =>  (c, basePrice.map(_ + 10))
  }

  def handlePartialClaim: PartialFunction[PC, PC] = { 
    case (c@Req(id, l, Partial(claimId, percentage)), basePrice)  =>  (c, basePrice.map(_ + 20))
  }

  def handleZipCode: PartialFunction[PC, PC] = { 
    case (c@Req(id, Location(_, Some(zipCode)), _), price) => (c, price.map(_ + 5)) 
  }

  def handleStateCode: PartialFunction[PC, PC] = { 
    case (c@Req(id, Location(Some(stateCode), _), _), price) => (c, price.map(_ + 10)) 
  }

  def claimHandlers = handleFullClaim orElse handlePartialClaim
  def locationHandlers = handleZipCode orElse handleStateCode

  def default: PartialFunction[PC, PC] = { case p => p }
  def priceCalculator: PartialFunction[PC, PC] = 
    (claimHandlers andThen locationHandlers) orElse default

  def main(args: Array[String]) = {
    priceCalculator((Req("some product", Location(None, Some("43230")), Full(1)), Some(10))) match {
      case (c, finalPrice) => println(finalPrice)
    }
    priceCalculator((Req("some product", Location(None, None), Generic(10)), Some(10))) match {
      case (c, finalPrice) => println(finalPrice)
    }
  }

}

What does the following snippet mean in scala: c@Req? Especially: what is the meaning of the @ sign here?

balteo
  • 23,602
  • 63
  • 219
  • 412
  • 1
    See this exact question: http://stackoverflow.com/questions/20748858/pattern-matching-symbol/20748908#20748908 "The meaning of @ in pattern matching" – wheaties Jan 21 '14 at 17:50

1 Answers1

4

In a pattern match @ binds the variable on the left to the value that is matched on the right. In your code c can then be referred to with the value of that pattern that was matched.

See this http://www.artima.com/pins1ed/case-classes-and-pattern-matching.html

Brian
  • 20,195
  • 6
  • 34
  • 55
  • Thanks. If I understand correctly, "`c`" is an instance of "`case class Req(productId: String, location: Location, claim: Claim)`"? Am I right? – balteo Jan 21 '14 at 17:38
  • 1
    Not necessarily; `c` matches the pattern `Req(id, l, Full(claimId))`. The `@` symbol allows you to specify both a capture and a pattern which must be matched by the captured value. – J Cracknell Jan 21 '14 at 19:24