简体   繁体   中英

How does Scala's Try type work under the hood?

It seems that Try doesn't exhibit behavior I'd expect from a type in how it's able to catch exceptions. I took a look at the source code , but still don't see how it works.

Is it using some Scala feature I'm unfamiliar with or is this treated specially by the compiler?

Nothing special here. Look at the apply method:

def apply[T](r: => T): Try[T] =
    try Success(r) catch {
      case NonFatal(e) => Failure(e)
    }

It's literally just wrapping try / catch by trying to return Success(r) , and if that fails, it returns Failure(e) .

It's all there:

https://github.com/scala/scala/blob/2.11.x/src/library/scala/util/Try.scala#L192

def apply[T](r: => T): Try[T] =
  try Success(r) catch {
    case NonFatal(e) => Failure(e)
}
  import scala.util._
  import scala.util.control.NonFatal

Next 3 lines will use the same apply method on scala.util.Try object:

  val res = Try.apply(throw new Exception)
  val res2 = Try(throw new Exception)
  val res3 = Try { throw new Exception }

which has the following definition:

  def apply[T](r: => T): Try[T] =
    try Success(r) catch {
      case NonFatal(e) => Failure(e)
    }
  1. apply method is defined with ByName parameter r , which is evaluated only when used. In our case it will be used in try block for Success(r) .
  2. By convention in Scala you can use parentheses to call object's apply method.
  3. Also by convention you can use curly braces to pass a single argument to method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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