Hannes
Hannes

Reputation: 5262

Using Try out of Exception contexts

Is it in Scala acceptable to use Try (Success/Failure) outside of an actual Exception context as a return type of a function that can succeed or fail?

Upvotes: 0

Views: 88

Answers (2)

Mario Galic
Mario Galic

Reputation: 48410

Instances of Try, are either Success or Failure, where Failure is

case class Failure[+T](exception: Throwable)

Note how Failure must be constructed with Throwable, so I think Try is meant to be used within context of Throwables. So we cannot do something like

def foo: Try[Int] = {
  Failure(42) // Error: type mismatch; found : Int(42) required: Throwable
}

Consider using Either instead of Try outside exceptions context.


Addressing the comment consider

In neither of these are you forced to use exceptions.

Here is an example

sealed trait MyValidationADT[T]
case class Good[T](result: T) extends MyValidationADT[T]
case class Bad[T](result: T) extends MyValidationADT[T]

def foo(i: Int): MyValidationADT[Int] = Bad(42)

foo(11) match {
  case Good(result) => "woohoo"
  case Bad(result) => "boom"
}

which outputs

res0: String = boom

Upvotes: 2

Tim
Tim

Reputation: 27356

It is certainly possible to use a Try outside an exception context; I use it that way all the time. That does not necessarily mean that it is "acceptable" :)

I would say that the whole point of using Try is to take the Throwable instance out of the exception context and put it in an object that can be used anywhere in a program. It is hard to see why Try would have such a rich set of methods (e.g. flatMap) if it is only intended to be used inside an exception context.

Upvotes: 3

Related Questions