那天我注意到了这个有趣的语法,用于指定Scala类的类型参数。用于指定类型参数的Scala中缀语法的名称是什么?
scala> class X[T, U]
defined class X
scala> new (Int X Int)
res1: X[Int,Int] = [email protected]
是否有这种语法的名称?什么是它的好用例?
那天我注意到了这个有趣的语法,用于指定Scala类的类型参数。用于指定类型参数的Scala中缀语法的名称是什么?
scala> class X[T, U]
defined class X
scala> new (Int X Int)
res1: X[Int,Int] = [email protected]
是否有这种语法的名称?什么是它的好用例?
下面是第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”。
这只是infix应用程序的二进制类型的构造函数。与中缀应用方法一样,当类型构造函数或方法的名称包含标点符号时,它更常用。 2.8库中的示例包括<:<
,<%<
和=:=
(参见scala.Predef
)。
哦,顺便说一下,术语“infix”用于这些类型。 – 2010-07-08 03:21:42