匹配时,您是否在case语句中动态创建变量?

时间:2013-07-03 17:50:32

标签: scala pattern-matching

我正在查看此scala代码并混淆变量partitionedData来自case Some(partitionedData)语句的位置:

private def dispatchSerializedData(messages: Seq[KeyedMessage[K,Message]]): Seq[KeyedMessage[K, Message]] = {
    val partitionedDataOpt = partitionAndCollate(messages)
    partitionedDataOpt match {
      case Some(partitionedData) =>
        val failedProduceRequests = new ArrayBuffer[KeyedMessage[K,Message]]
        try {
          for ((brokerid, messagesPerBrokerMap) <- partitionedData) {
            if (logger.isTraceEnabled)
              messagesPerBrokerMap.foreach(partitionAndEvent =>
                trace("Handling event for Topic: %s, Broker: %d, Partitions: %s".format(partitionAndEvent._1, brokerid, partitionAndEvent._2)))
            val messageSetPerBroker = groupMessagesToSet(messagesPerBrokerMap)

            val failedTopicPartitions = send(brokerid, messageSetPerBroker)
            failedTopicPartitions.foreach(topicPartition => {
              messagesPerBrokerMap.get(topicPartition) match {
                case Some(data) => failedProduceRequests.appendAll(data)
                case None => // nothing
              }
            })
          }
        } catch {
          case t: Throwable => error("Failed to send messages", t)
        }
        failedProduceRequests
      case None => // all produce requests failed
        messages
    }
  }

在比赛中,您是否即时创建变量?它是否等于partitionedDataOpt?

1 个答案:

答案 0 :(得分:2)

partitionedDataOptOption,可以是Some(value)None(两者都是Option的子类型)

如果partitionedDataOptSome选项,它会将实际值包含在内部,模式匹配标记partitionedData作为选项中包含的值。在这种情况下,您可以根据需要为其命名,并且它在匹配的案例中是本地的。

  

在比赛中,您是否即时创建变量?

你可以这么说,我认为partitionedData可以看作是case条款中的本地val

  

是否等于partitionedDataOpt?

如果 partitionedDataOpt有值(例如partitionedDataOpt.get

,则可以说它等于Some

Options Some None并非Option只是案例类/** Class `Some[A]` represents existing values of type * `A`. * * @author Martin Odersky * @version 1.0, 16/07/2003 */ final case class Some[+A](x: A) extends Option[A] { def isEmpty = false def get = x } /** This case object represents non-existent values. * * @author Martin Odersky * @version 1.0, 16/07/2003 */ case object None extends Option[Nothing] { def isEmpty = true def get = throw new NoSuchElementException("None.get") } source

{{1}}