Thursday, November 5, 2009

Programming in Scala: Chapter 19 - Type Parameterization

Some notes from the chapter-19 from the book "Programming in Scala".

Type parameterization allows you to write generic classes and traits in scala.

Whether a type parameter is covariant, contravatiant or nonvariant, its called parameter's variance.

The + or - symbols, you can place, before the type parameters(to make it covariant,contravariant respectively) are called variance annotations.

In general, If a classes type parameter is also one of the argument's parameter of a method, its not possible to have that parameter covariant. It is not allowed because of being unsafe. See the book for plenty of example describing why.

Methods can also declare type parameters. So we can't have unsafe thing like..
class Queue[+T] {
def append(x: T)

but, can have
class Queue[T] {
def append[U <: T](x: U)

This sort of design is called type-driven design, where the type of class/trait "guides" its details and implementation.

Liskov Substitution Principle: In type driven design: it is safe to assume that a type T is subtype of type U if you can substitute a value of type T wherever a value of U is required. The principle holds if T supports all operations that of U and require less but more than the corresponding operation in U.

Note: Queue is not a type but type constructor; Queue[String], Queue[Int] etc are types.

No comments:

Post a Comment