简体   繁体   English

Scala尝试[单位]混乱

[英]Scala Try[Unit] confusion

I have this piece of code 我有这段代码

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

and 2 questions: 和2个问题:

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

You are basically forcing compiler to assign Try as Unit . 您基本上是强制编译器分配Try as 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 () . 例如,下面的doSomething方法应该返回Int因为它是最后一个语句,但返回类型Unit强制它返回()

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

In your example val t: Try[Unit] = Try(Try(1 / 0)) , you asking compiler to treat inner Try(1 / 0) as Unit ; 在你的例子中val t: Try[Unit] = Try(Try(1 / 0))你要求编译器将内部Try(1 / 0)视为Unit ; which means 意思是

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

Which means even if Try fails, its Unit which is always Success for another Try that you have. 这意味着即使Try失败,它的Unit总是Success另一个Try你拥有。

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

Better remove the specific type you are providing and let the compiler figure it out, 最好删除您提供的特定类型,让编译器弄明白,

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

Also read: Scala: Why can I convert Int to Unit? 另请阅读: Scala:为什么我可以将Int转换为Unit?

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

Try(1) returns Success(1) . Try(1)返回Success(1) Try(Try(1) returns Success(()) because of its assignment to Type Try[Unit] Similar to the following commands in Scala REPL where x is forced to take Unit type: Try(Try(1)返回Success(())因为它分配给Type Try[Unit]类似于Scala REPL中的以下命令,其中x被强制取Unit类型:

scala> val x = 5
x: Int = 5

scala> val x:Unit = 5
<console>:23: warning: a pure expression does nothing in statement position; you may be omitting necessary parentheses
       val x:Unit = 5
                    ^
x: Unit = ()

scala>

So obviously the compiler is taking the return value and is forced to type () which is Unit . 很明显,编译器正在获取返回值并被强制输入() ,即Unit Because it is Unit may be it makes sense the way compiler interprets it. 因为它是Unit可能是编译器解释它的方式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM