2

我正在查看此 scala 代码,并且partitionedDatacase 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 吗?

4

1 回答 1

2

partitionedDataOpt是 aOption并且可以是 aSome(value)或 a None(两者都是 的子类型Option

如果partitionedDataOpt是一个Some选项,它将实际值包装在里面,并且模式匹配标记partitionedData为选项中包含的值。在这种情况下,您可以随意命名它,并且它是匹配案例的本地名称。

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

可以这么说,我觉得partitionedData可以看成是局部val作用于case子句

它等于 partitionedDataOpt 吗?

partitionedDataOpt.get 如果partitionedDataOpt 有一个值(例如 a Some),您可以说它等于

Options顺便说一下,它不是唯一的SomeNone只是扩展的案例类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")
}
于 2013-07-03T18:14:47.450 回答