Scala意思是以下语法:“c @Req”

时间:2014-01-21 17:25:51

标签: scala

我对以下部分代码有疑问:

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)
    }
  }

}

以下代码段在scala中的含义是什么: c@Req ?特别是: @ 符号的含义是什么?

1 个答案:

答案 0 :(得分:4)

在模式匹配@中,将左侧的变量绑定到右侧匹配的值。然后,您的代码c可以使用匹配的模式的值来引用。

请参阅此http://www.artima.com/pins1ed/case-classes-and-pattern-matching.html