I noticed this interesting syntax the other day for specifying the type parameters for a Scala class.
scala> class X[T, U]
defined class X
scala> new
Here's an example from "Programming Scala" (O'Reilly), page 158 in Chapter 7, "The Scala Object System", which we adapted from Daniel Scobral's blog (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)
}
Either is a built-in type and this idiom is common in some functional languages as an alternative to throwing an exception. Note that you Left and Right are subtypes of Either. Personally, I wish the type were named "Or", so you could write "Throwable Or T".
It's just infix application of a binary type constructor. As with infix application of methods, it's more commonly used when the name of the type constructor or method comprises punctuation characters. Examples in the 2.8 library include <:<
, <%<
and =:=
(see scala.Predef
).