Scala Try[Unit] confusion

后端 未结 2 632
滥情空心
滥情空心 2021-01-21 00:23

I have this piece of code

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

and 2 questions:

  • What is happening here? How can t
2条回答
  •  一向
    一向 (楼主)
    2021-01-21 00:35

    You are basically forcing compiler to assign 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 ().

    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; 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.

    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?

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

提交回复
热议问题