Ecco un esempio di "Programmazione Scala" (O'Reilly), pagina 158 nel capitolo 7, "Il sistema di oggetti Scala", che abbiamo adattato dal blog di Daniel Scobral (http://dcsobral.blogspot .com/2009/06/eccezioni di cattura html):
// code-examples/ObjectSystem/typehierarchy/either-script.scala
def exceptionToLeft[T](f: => T): Either[java.lang.Throwable, T] = try { Right(f)
} catch {
}
case ex => Left(ex)
def throwsOnOddInt(i: Int) = i % 2 match { case 0 => i
}
case 1 => throw new RuntimeException(i + " is odd!")
for(i <- 0 to 3) exceptionToLeft(throwsOnOddInt(i)) match {
}
case Left(ex) => println("exception: " + ex.toString) case Right(x) => println(x)
O è un tipo incorporato e questo linguaggio è comune in alcuni linguaggi funzionali come alternativa a un'eccezione. Nota che Left e Right sono sottotipi di Either. Personalmente, vorrei che il tipo venisse chiamato "Or", quindi potresti scrivere "Throwable Or T".
fonte
2010-07-08 03:20:44
Oh, a proposito, il termine "infisso" viene utilizzato per questi tipi. –