Richard Searle's Blog

Thoughts about software

A change in typing philosophy, indicated by Scala type classes

Posted by eggsearle on September 6, 2010

This discussion provides a clear and useful discussion of how Scala type classes might be used.

The code requires that a type be specified, which then indirectly defines the code to be executed

val i = foo[Int]("123") // 123
val f = foo[Float]("123.0") // 123.0

Where i and f will have types Int and Float respectively.

Coming from other strongly typed languages, one might be tempted to write

val i:Int = foo("123") // 123
val f:Float = foo("123.0") // 123.0

Which does not work. It might be argued that the type inferencer should be sophisticated enough to map this code to the earlier form.

Ignoring any technical reasons that prohibit the second form (or would lead to undesirable ambiguities), there are other reasons for prefer the first style.

  • The type is placed right next to the affected code, which is always helpful.
  • Passing the result of foo as an argument to a method is straightforward and well defined (even in the face of methods overloaded on argument type).
  • Conforms to the Scala style of only typing vals where absolutely necessary.
  • Conforms to the functional style which minimises temporary variables.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: