tags:

views:

131

answers:

3

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 (Int X Int)
res1: X[Int,Int] = X@856447

Is there a name for this sort of syntax? What's a good use case for it?

+2  A: 

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".

Dean Wampler
Oh, and by the way, the term "infix" is used for these types.
Dean Wampler
+5  A: 

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).

Randall Schulz
+2  A: 

Google may be your friend. First hit on "Scala infix type" is http://jim-mcbeath.blogspot.com/2008/11/scala-type-infix-operators.html.

huynhjl
Very informative blog post. Thanks!
dave