gpt4 book ai didi

scala - 在 Scala 中尝试惰性 val 上的模式匹配?

转载 作者:行者123 更新时间:2023-12-04 03:04:24 25 4
gpt4 key购买 nike

是否可以对声明为 Trylazy val 进行模式匹配,如下所示?

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)
}

最佳答案

这绝对有可能,您只是导入了错误的 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,您可以用它做您想做的事情。

关于scala - 在 Scala 中尝试惰性 val 上的模式匹配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46431096/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com