Reputation: 14899
I'm looking at this scala code and confused where the variable partitionedData
is coming from in the case Some(partitionedData)
statement:
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
}
}
During a match, do you create a variable on the fly? is it equal to partitionedDataOpt ?
Upvotes: 2
Views: 109
Reputation: 45765
partitionedDataOpt
is an Option
and can be either a Some(value)
or a None
(both are subtypes of Option
)
If partitionedDataOpt
is a Some
Option, it wraps the actual value inside, and the pattern matching marks partitionedData
as the value contained in the option. In that case you can name it however you want, and it is local to the matched case.
During a match, do you create a variable on the fly?
You can say so, I think partitionedData
can be seen as a local val scoped in the case
clause
is it equal to partitionedDataOpt ?
You can say it's equal to partitionedDataOpt.get
if partitionedDataOpt has a value (e.g. a Some
)
It is not unique to Options
by the way Some
and None
are simply case classes extending Option
(source)
/** 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")
}
Upvotes: 2