定义嵌套的strucType

时间:2018-08-22 12:03:15

标签: scala dictionary option

我有以下问题: 具有元素列表的选项,我想通过避免在选项上使用.get来将其转换为元素列表。 下面是我要更改的代码段:任何想法请修改它:

val receivedMessages = PubSubClient.getPulledMessages(client,subscriptionFullName,pullRequest).get
        store(receivedMessages
          .map(x => {
            val sm = new PubsubSparkMessage
            sm.message = x.getMessage
            sm
          })
          .iterator)

我要替换PubSubClient.getPulledMessages(client,subscriptionFullName,pullRequest).get行中的.get

最好的问候

2 个答案:

答案 0 :(得分:0)

以这个例子为例:

val maybeList = Some(List("hello", "here"))

打印此文件时:

println(maybeList) // Some(List(hello, here))

要解决此问题,您可以执行以下操作:

maybeList.toSeq.flatMap(x=> x) // List(hello, here)

或者,如果您愿意与之配合,则:

for{
  list <- maybeList.toSeq
  elem <- list
} yield elem

或者简而言之:

maybeList.toSeq.flatten

如果您想玩此游戏,请在这里Scala Fiddle

以您的示例为例-

val receivedMessages = PubSubClient.getPulledMessages(client,subscriptionFullName,pullRequest)

store(receivedMessages.toSeq
      .flatMap(x => {
        val sm = new PubsubSparkMessage
        sm.message = x.getMessage
        sm
      })

答案 1 :(得分:0)

This function will accomplish what you want:

def listOptToList[T](listOpt: Option[List[T]): List[T] = listOpt.toList.flatten

So your code would look something like:

val receivedMessages = PubSubClient.getPulledMessages(client,subscriptionFullName,pullRequest)

store(listOptToList(receivedMessages.map { x =>
    val sm = new PubSubSparkMessage
    sm.message = x.getMessage
    sm
  }).iterator)