Scala Try[Unit]混淆 [英] Scala Try[Unit] confusion

查看:43
本文介绍了Scala Try[Unit]混淆的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这段代码

import scala.util.Try
val t: Try[Unit] = Try(Try(1))

和 2 个问题:

  • 这里发生了什么?Try[Try[Int]] 类型如何匹配尝试[单位]?是不是因为Scala为block选择了返回类型Try(1) 成为 Unit 以匹配所需类型?
  • 无论如何检测嵌套的Try?说我有一个 Try[A],我怎么知道 A 是否是另一个 Try[_]?
  • What is happening here? How can the type Try[Try[Int]] match with Try[Unit]? Is it because Scala chooses the return type for block Try(1) to be Unit to match with the desired type?
  • Is there anyway to detect a nested Try? Says I have a Try[A], how do I know if A is another Try[_]?

推荐答案

您基本上是在强制编译器将 Try 分配为 Unit.

You are basically forcing compiler to assign Try as Unit.

例如,下面的 doSomething 方法应该返回 Int 作为最后一条语句,但是返回类型 Unit 迫使它返回 <代码>().

For exmple doSomething method below is supposed to return Int as that is last statement, but return type Unit is forcing it to return ().

scala> def doSomething: Unit = 1 + 1
doSomething: Unit

在您的示例中 val t: Try[Unit] = Try(Try(1/0)), 您要求编译器处理内部 Try(1/0) 作为 Unit;这意味着

scala> val innerTry: Unit = Try(1 / 0)
innerTry: Unit = ()

这意味着即使 Try 失败,它的 Unit 对于另一个 Try 总是 Success.

Which means even if Try fails, its Unit which is always Success for another Try that you have.

scala> val t: Try[Unit] = Try(someOperation)
t: scala.util.Try[Unit] = Success(())

最好删除您提供的特定类型并让编译器找出来,

scala> val t = Try(Try(1 / 0))
t: scala.util.Try[scala.util.Try[Int]] = Success(Failure(java.lang.ArithmeticException: / by zero))

另请阅读:Scala:为什么我可以将 Int 转换为 Unit?

final abstract class Unit private extends AnyVal {
  // Provide a more specific return type for Scaladoc
  override def getClass(): Class[Unit] = ???
}

这篇关于Scala Try[Unit]混淆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆