Saturday, December 26, 2009

As a response to a comment on a previous post about about Tuples this topic is about Products and the most common subclasses of Tuples.

I should preface this post by saying that I am not going to attempt any scholastic style discussions, instead I am going to try to explain Product in practical terms and stay away from theory. That said on can think of Products as (potentially) heterogenous collections (non-resizable collections). There are several Product classes (Product, Product1, Product2...). All Product classes extend Product, which contains the common methods. Product has the methods for accessing the Product members and the subclass adds type information about the Members.

Friday, December 18, 2009

Tuples are quite handy but a potential annoyance is that at a glance they seem list-like but appearances can be deceiving. The normal collection methods are not supported by Tuples. For example suppose you like the simple syntax: (1,2,3) better than List(1,2,3). With the Tuple you cannot do the maps, filters, etc... (with good reason) but there is a use-case for being able to convert a Tuple to a Traversable.

Word of warning. Unlike collections Tuples are very often not homogeneous. IE you do not have Tuple2[Int] you have Tuple2[A,B]. So the best you can do is to map a tuple to an Iterator[Any].

Note: this was done with Scala 2.8 so results may be slightly different with 2.7. But I believe the syntax is valid.

// the productIterator method gives access to an iterator over the elements

scala> (1,2,3).productIterator.map {_.toString} mkString (",")

res1: String = 1,2,3

scala> (1,2,3).productIterator foreach {println _}

1

2

3

// if you know the tuple is heterogeneous then you can use partial functions

Wednesday, December 16, 2009

This is the second Scala test framework topic and focuses on the excellent Specs framework. The other topic was on ScalaTest, another excellent testing framework for Scala.

Specs is focussed on BDD testing (Behaviour Driven Design) and is the inspiration for ScalaTests WordSpec. From what I understand Specs was in-turn inspired by RSpec the Ruby BDD testing framework.

Specs has some truly unique features to it which we will encounter in future topics. But for now just the basics. The following example tests a couple of Scala's XML support in order to demonstract the general pattern followed when writing Specs' tests.

Sunday, December 13, 2009

It is possible (although not recommended) to declare a public property in a super class and have a private value or variable in a subclass:

scala>class X (val i:Int)

defined class X

scala>class Y(i:Int) extends X(19) {

| println(i)

| }

defined class Y

scala>val y = new Y(100)

100

y: Y = Y@3e55a58f

scala> y.i

res7: Int = 19

This begs the question: how can the subclass access the superclass instance of i? Let me re-iterate. Just because it is possible this is a bad idea. This pattern seems like it is begging to create bugs. But who knows there is probably some reason out there where this is required.

The way to access the X.i value from Y is to declare which value you want using the syntax this:X :

scala>class Y(i:Int) extends X(19) {

| println("Y.i"+i)

| println("X.i"+(this:X).i)

| }

defined class Y

scala>new Y(39)

Y.i39

X.i19

res8: Y = Y@451dfada

Repeat: Watch out! Because I learned this danger while writing this topic:

scala>class Y(i:Int) extends X(19) {

| println("1. "+i)

| println("2. "+this.i)

| println("3. "+(this:Y).i)

| println("4. "+(this:X).i)

| }

defined class Y

scala>new Y(44)

1. 44

2. 44

3. 19 // this is created via (this:Y).i !

4. 19

res0: Y = Y@338bd37a

It seems that the syntax (this:X).i accesses the public accessor for i. The public access is a method call I think so it always obtains the value for the property. Shocking!

Thursday, December 10, 2009

This topic is a continuation of XML Transformations. The previous topic showed a method of creating transformation rules then combining the rules to create a transformation that could be applied to an XML datastructure. This topic takes a different approach ofusing a match statement an a recursive method to iterate through the tree.

Wednesday, December 9, 2009

Futures are mainly tokens returned by an actor that promises a result sometime in the future. The typical place one encounters a future is from an actor. The !! method of an actor returns a future. However in addition the Futures object provides several methods for doing parallel processing without having to write actors (or threads for that matter.)

Note: My use of scala.util.Random requires Scala 2.8 but I think the rest is 2.7.7.

scala>import scala.actors.Futures._

import scala.actors.Futures._

/*

The most basic future example.

Just runs the function in a seperate thread and returns a Future object

for the result

*/

scala> future {Thread.sleep(10000);println("hi");10}

res2: scala.actors.Future[Int] = < function0>

/*

Use one of the future methods for obtaining the actual result

this one blocks tile ready, but other can check if result is ready and so on

*/

scala> res2()

hi

res3: Int = 10

/*

This is more interesting.

The method creates several futures and the using the awaitAll method

waits for all the futures to complete before continuing

*/

scala>def bubbles = {

| val bubbles = for( i <- 1 to 20) yield {

| future {

| Thread.sleep(scala.util.Random.nextInt(20)*500)

| println("pop "+i)

| "pop "+i

| }

| }

| awaitAll(30000, bubbles:_*) foreach println _

| }

bubbles: Unit

scala> bubbles

pop 9

pop 12

pop 11

pop 5

pop 3

pop 14

pop 20

pop 10

pop 1

pop 4

pop 16

pop 6

pop 7

pop 2

pop 8

pop 18

pop 15

pop 19

pop 17

pop 13

Some(pop 1)

Some(pop 2)

Some(pop 3)

Some(pop 4)

Some(pop 5)

Some(pop 6)

Some(pop 7)

Some(pop 8)

Some(pop 9)

Some(pop 10)

Some(pop 11)

Some(pop 12)

Some(pop 13)

Some(pop 14)

Some(pop 15)

Some(pop 16)

Some(pop 17)

Some(pop 18)

Some(pop 19)

Some(pop 20)

scala>import java.net._

import java.net._

scala>import scala.io._

import scala.io._

/*

A kind of funny example. We set off two futures to download the google page

This topic is really just a collection of examples using the Scala 2.8 API. The examples are mostly based on Strings. But because Strings are in fact an IndexedSeq all of these examples also work with Lists arrays and the first several work with all collections.

These examples are all based on first Traversable. The basis of all collections and therefore will work with all collections. And the next set of examples work with IndexedSeq and most will work with Seq as well. Sets, Maps and others still need to be examined.

This is not an exhaustive set of examples and not all are even that interesting (sorry :-) ). But I let out the most trivial unless theay are being compared to others.

Traversable:

scala>val license = """Subject of Agreement. ?Product?, as referred to in this Agreement, shall be the binary software package ?Sun VirtualBox,? which Product allows for creating multiple virtual computers, each with different operating systems (?Guest Computers?), on a physical computer with a specific operating system (?Host Computer?), to allow for installing and executing these Guest Computers simultaneously. The Product consists of executable files in machine code for the Solaris, Windows, Linux, and Mac?OS?X operating systems as well as other data files as required by the executable files at run-time and documentation in electronic form. The Product includes all documentation and updates provided to You by Sun under this Agreement and the terms of this Agreement will apply to all such documentation and updates unless a different license is provided with an update or documentation."""

res47: String = Sbjct f Agreement. ?Product?, s referred to n this Agreement, shall be the binary software package ?Sun VirtualBox,? which Product allows for creating multiple virtual computers, each with different operating systems (?Guest Computers?), on a physical computer with a specific operating system (?Host Computer?), to allow for installing and executing these Guest Computers simultaneously. The Product consists of executable files in machine code for the Solaris, Windows, Linux, and Mac?OS?X operating systems as well as other data files as required by the executable files at run-time and documentation in electronic form. The Product includes all documentation and updates provided to You by Sun under this Agreement and the terms of this Agreement will apply to all such documentation and updates unless a different license is provided with an update or documentation.

scala> license dropRight(30)

res48: String = Subject of Agreement. ?Product?, as referred to in this Agreement, shall be the binary software package ?Sun VirtualBox,? which Product allows for creating multiple virtual computers, each with different operating systems (?Guest Computers?), on a physical computer with a specific operating system (?Host Computer?), to allow for installing and executing these Guest Computers simultaneously. The Product consists of executable files in machine code for the Solaris, Windows, Linux, and Mac?OS?X operating systems as well as other data files as required by the executable files at run-time and documentation in electronic form. The Product includes all documentation and updates provided to You by Sun under this Agreement and the terms of this Agreement will apply to all such documentation and updates unless a different license is provided wi

res27: String = eeet. ?rouct?, referred to n tis Agreement, shal be the binar softare acage ?Sun irtualo,? which Product allows for creating multiple irtual computers, each with different operating systems (?uest omputers?), on a physical computer with a specific operating system (?ost Computer?), to allow for installing and executing these Guest Computers simultaneously. he Product consists of executable files in machine code for the Solaris, indows, inux, and ac?S? operating systems as well as other data files as reuired by the executable files at run-time and documentation in electronic form. The Product includes all documentation and updates provided to ou by Sun under this Agreement and the terms of this Agreement will apply to all such documentation and updates unless a different license is provided with an update or documentation.

While at a glance the underscores do not seem related, in fact the general rule is fill in the blank. Sca_la what goes in the blank?

Going through the examples:

import anything/everything in package

this seems to be an exception. Assign File to oblivion. (It is no longer imported)

import all methods in object

same thing. Import all methods in instance object

creat a new method where the first parameter is defined but all others will be defined later. In this case a special syntax is required so the compiler knows that a new method is desired and the missing parameters was not simply a mistake. There is another syntax for defining methods that do not require the _ for currying

reduceLeft takes method with 2 parameters. _ + _ creates a function of 2 parameters: the first '_' represents the first parameter and the second '_' represents the second parameter.

the '_' represents any value. This syntax is frowned upon since Scala has such a rich type system but can be useful when interoperating with Java. Perhaps a better declaration would be Generic[Any]

Search This Blog

About Me

Jesse EicharI am a senior software developer at Camptocamp SA (Swiss office) and specialize in open-source geospatial Java projects. I am a member of the uDig steering committee and a contributor to Geotools and Mapfish. In addition I regularly work with Geoserver and Geonetwork.

In my free time I am a Scala enthusiast. I am working on the Scala IO incubator project and WebSpecs a Specs2 based testing framework for webapplications.