Scala中的Try lazy val上的模式匹配?

时间:2017-09-26 16:01:23

标签: scala akka

是否可以对lazy val进行模式匹配,声明为Try,就像这样?

lazy val kafkaProducer: Try[producer.KafkaProducer[Array[Byte], String]] = Try(kafkaProducerSettings.createKafkaProducer())
...
kafkaProducer.get match {
  case Success(_) => Source.single(producerRecord()).runWith(Producer.plainSink(kafkaProducerSettings, kafkaProducer.get))
  case Failure(x) => Future.failed(x)
}

我收到此错误:

constructor cannot be instantiated to expected type;
[error]  found   : akka.actor.Status.Success
[error]  required: org.apache.kafka.clients.producer.KafkaProducer[Array[Byte],String]
[error]         case Success(_) => Source.single(producerRecord()).runWith(Producer.plainSink(kafkaProducerSettings, kafkaProducer.get))

请注意,此替代代码有效,但我不确定它是" Scala方式":

lazy val kafkaProducer: producer.KafkaProducer[Array[Byte], String] = kafkaProducerSettings.createKafkaProducer()
...
val tryAccessLazyKafkaProducer = Try(kafkaProducer)
if (tryAccessLazyKafkaProducer.isSuccess) {
  Source.single(producerRecord()).runWith(Producer.plainSink(kafkaProducerSettings, kafkaProducer))
} else {
  Future.failed(tryAccessLazyKafkaProducer.failed.get)
}

1 个答案:

答案 0 :(得分:5)

这绝对可能,您输入错误的Success类型:

found   : akka.actor.Status.Success

您需要scala.util.Success

你不能做的一件事是调用Try.get,如果返回的类型是Failure,它将会爆炸。相反,做:

import scala.util.Success
import scala.util.Failure

kafkaProducer match {
    case Success(producer) => Source.single(producerRecord()).runWith(Producer.plainSink(kafkaProducerSettings, producer))
    case failure: Failure => failure
}

lazy只是一种语言结构,可以确保只对值进行一次评估。底层类型,无论是否懒惰,仍然是Try,你可以用它来做它。