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?
For a long time, Scala has supported a useful “trick” called infix operator notation. If a method takes a single argument, you can call it without the period after the instance and without parentheses around the argument.
Scala is a statically typed programming language. This means the compiler determines the type of a variable at compile time. Type declaration is a Scala feature that enables us to declare our own types.
=> is syntactic sugar for creating instances of functions. Recall that every function in scala is an instance of a class. For example, the type Int => String , is equivalent to the type Function1[Int,String] i.e. a function that takes an argument of type Int and returns a String .
Non-value types capture properties of identifiers that are not values. For example, a type constructor does not directly specify a type of values. However, when a type constructor is applied to the correct type arguments, it yields a first-order type, which may be a value type.
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
).
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".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With