gpt4 book ai didi

scala - 将 Future[Unit] 分配给 Unit

转载 作者:行者123 更新时间:2023-12-03 14:59:50 28 4
gpt4 key购买 nike

为什么这样编译

scala> import scala.concurrent.Future
import scala.concurrent.Future

scala> val f: Unit = Future.successful(())
f: Unit = ()

我希望编译器会提示分配。

最佳答案

这称为“值(value)丢弃”。引用 scala specification (6.26.1) :

Value Discarding

If e has some value type and the expected type is Unit, e is converted to the expected type by embedding it in the term { e; () }.



换句话说,任何值,无论其类型如何,都会隐式转换为 Unit ,有效地丢弃它。

如果您想收到有关此类丢弃的警告(在某些情况下可以隐藏错误),您可以通过 -Ywarn-value-discard编译器的选项。然后你必须明确返回 ()每次调用一个方法只是为了它的副作用,但该方法确实返回一个非 Unit 值。

关于scala - 将 Future[Unit] 分配给 Unit,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32713445/

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