How can we teach the utility of Try?

154 views
Skip to first unread message

Rex Kerr

unread,
Apr 29, 2013, 6:58:45 PM4/29/13
to scala-debate
I've noticed repeatedly on StackOverflow (and also scala-users) that even some of the most sophisticated members of the Scala community write suboptimal-clarity Try code.

When I use Try, I make heavy use of two patterns:

(1) Assume the best, prepare for the worst.

  val x = Try { ... }
  val y = Try { ... }
  val z = Try { ...; f(x.get, y.get); ... }

(This is/should be the answer to pretty much every question of the form "I have Try inside and I want it outside".)

(2) Exceptions are classes, too.

  case class Net(fish: String) extends Exception
  Try { ...; throw Net("salmon"); ... } match {
     case Failure(Net(fish)) => println("Oh, it's just a "+fish)
     case Failure(t) => ...
     case Success(s) => ...
  }

(This is/should be the answer to pretty much every question of the form "Sometimes I need to return some data along with a failure.")

I'm sure there are more.  But it seems--am I wrong?--that these sorts of patterns are not really occurring naturally to people.

Why not, and what can we do about it (or is there something wrong with these patterns?--yes, I know it's a pretty heavyweight fishing operation there)?

  --Rex

marius a. eriksen

unread,
Apr 29, 2013, 7:34:22 PM4/29/13
to Rex Kerr, scala-debate
The initial idea behind com.twitter.util.Try -- from which
scala.util.Try is derived -- was to divorce exception handling from
the call stack. Where you can get away with normal exception handling,
consider using stack-based exception handling, otherwise use Try.

-marius

Julien Richard-Foy

unread,
May 6, 2013, 6:33:37 AM5/6/13
to scala-...@googlegroups.com
I think Try gives you more control than try because it turns “computation attempts” into first class values.
Reply all
Reply to author
Forward
0 new messages