前几天我注意到了这个有趣的语法,用于指定Scala类的类型参数.
scala> class X[T, U]
defined class X
scala> new (Int X Int)
res1: X[Int,Int] = X@856447
Run Code Online (Sandbox Code Playgroud)
这种语法有名称吗?它的用例是什么?
Ran*_*ulz 11
它只是二进制类型构造函数的中缀应用程序.与中缀应用方法一样,当类型构造函数或方法的名称包含标点符号时,更常用.在2.8库的实例包括<:<,<%<和=:=(见scala.Predef).
以下是“Programming Scala”(O'Reilly)第 158 页第 7 章“Scala 对象系统”中的示例,我们改编自 Daniel Scobral 的博客 ( http://dcsobral.blogspot.com/2009/06/having ) -例外.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)
}
Run Code Online (Sandbox Code Playgroud)
两者都是内置类型,这种习惯用法在某些函数式语言中很常见,作为抛出异常的替代方法。请注意,Left 和 Right 是 Either 的子类型。就我个人而言,我希望该类型被命名为“Or”,这样你就可以写“Throwable Or T”。
| 归档时间: |
|
| 查看次数: |
2186 次 |
| 最近记录: |