Why Scala's Try has no type parameter for exception type? -



Why Scala's Try has no type parameter for exception type? -

i'm curious why scala.util.try has no type parameter exception type like

abstract class try[+e <: throwable, +t] { recoverwith[u >: t](f: partialfunction[e, try[e, u]]): try[e, u] ... }

would help documentation, e.g

def parseint(s: string): try[numberformatexception, int]

still won't able express disjoint exception types throws securityexception, illegalargumentexception, @ to the lowest degree 1 step in direction.

this might you're looking for:

import scala.util.control.exception._ import scala.util.{ success, failure } def foo(x: int): int = x match { case 0 => 3 case 1 => throw new numberformatexception case _ => throw new nullpointerexception } val success(3) = catching(classof[numberformatexception]).withtry(foo(0)) val failure(_: numberformatexception) = catching(classof[numberformatexception]).withtry(foo(1)) // val neverreturns = catching(classof[numberformatexception]).withtry(foo(2))

see scala.util.control.exception$

however, there's no way specialize try[t] hypothetical try[exctype, t]; in order work you'll need either (but perchance more sophisticated such scalaz.\/, or, more 1 exception class, shapeless' coproduct):

def bar(x: int): either[numberformatexception, int] = { catching(classof[numberformatexception]).withtry(foo(x)) match { case success(x) => right(x) case failure(exc) => left(exc.asinstanceof[numberformatexception]) } } println(bar(0)) // right(3) println(bar(1)) // left(java.lang.numberformatexception) // println(bar(2)) // throws nullpointerexception

it should possible generalize generic helper works number of exception types. you'd have work shapeless' coproduct , facilities abstracting on arity in case. unfortunately, it's non-trivial exercise , don't have time implement right now.

scala exception-handling try-catch algebraic-data-types

Comments

Popular posts from this blog

formatting - SAS SQL Datepart function returning odd values -

c++ - Apple Mach-O Linker Error(Duplicate Symbols For Architecture armv7) -

php - Yii 2: Unable to find a class into the extension 'yii2-admin' -