2010-07-08 25 views

回答

3

下面是第7章“The Scala对象系统”中的“Programming Scala”(O'Reilly)中的一个示例,我们改编自Daniel Scobral的博客(http://dcsobral.blogspot .com/2009/06/catching-exceptions 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) 

要么是一个内置的类型和此成语常见于某些功能的语言来替代抛出异常。请注意,您的Left和Right是Either的子类型。就我个人而言,我希望该类型被命名为“或”,因此您可以编写“Throwable或T”。

+1

哦,顺便说一下,术语“infix”用于这些类型。 – 2010-07-08 03:21:42

10

这只是infix应用程序的二进制类型的构造函数。与中缀应用方法一样,当类型构造函数或方法的名称包含标点符号时,它更常用。 2.8库中的示例包括<:<,<%<=:=(参见scala.Predef)。

相关问题