Scala Try[Unit] confusion

后端 未结 2 629
滥情空心
滥情空心 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:44

    Try(1) returns 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:

    scala> val x = 5
    x: Int = 5
    
    scala> val x:Unit = 5
    :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. Because it is Unit may be it makes sense the way compiler interprets it.

提交回复
热议问题