What advantages does scala.util.Try have over try..catch?

生来就可爱ヽ(ⅴ<●) 提交于 2019-11-30 20:11:19

I think you're having difficulty seeing the composition abilities of Try[T] because you're handling exceptions locally in both cases. What if you wanted to compose divideConventional with an additional operation?

We'd having some like:

def weNeedAnInt(i: Int) = i + 42

Then we'd have something like:

weNeedAnInt(divideConventional())

But let's say you want to max out the number of retries you allow the user to input (which is usually what you have in real life scenarios, where you can't re-enter a method forever? We'd have to additionally wrap the invocation of weNeedAnInt itself with a try-catch:

try {
  weNeedAnInt(divideConventional())
} catch {
   case NonFatal(e) => // Handle?
}

But if we used divide, and let's say it didn't handle exceptions locally and propogated the internal exception outwards:

def yetMoreIntsNeeded(i: Int) = i + 64

val result = divide.map(weNeedAnInt).map(yetMoreIntsNeeded) match {
  case Failure(e) => -1
  case Success(myInt) => myInt
}

println(s"Final output was: $result")

Is this not simpler? Perhaps, I think this has some subjectivity to the answer, I find it cleaner. Imagine we had a long pipeline of such operations, we can compose each Try[T] to the next, and only worry about the problems when once the pipeline completes.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!