Tuesday, March 22, 2011

How to run a project in Orion (Windows Vista)

Are you using Eclipse Project's Orion? Did you manage to link a folder so that you can edit the files inside it? Are you having problems with opening your finely crafted index.html under Windows? No problemo!

  1. Using wordpad or a serious texteditor (ultraedit, vi...), add the following line to your Orion eclipse.ini file, after the -vmargs line: -Dorg.eclipse.orion.server.hosting.virtualHosts=
  2. Open Windows Firewall using the Administrator rights, and add two rules: one for dropping all the connections to as local interface using TCP from all hosts, the other to open all the connections to using TCP coming from as remote interface
  3. Create a site configuration for your link
  4. Push the green "play" button on the sites lists
  5. Your linked project will be published at the address "" + "the value in the <<Mount at>> column" in the configuration

For example, if the Mount at value is "/mountPoint" you will find your index page under (and not at the default address).

When you feel more sure and you want to publish more projects simultaneously, you can remove the -Dorg.eclipse.orion.server.hosting.virtualHosts= line, and change your rules to cover the 127.0.0.* as "the local interface" (leave "all" as remote interface in the block-rule and "" as remote interface in the allow-rule) and then enjoy your Orion with multiple projects.

Monday, December 13, 2010

Stupid type mismatch while creating an execTask in sbt.

Let's say you create a new task in your SBT Project. You follow the instructions and add the new task as:

 execTask {
  <x>command --param {param1} {param2}</x>
 } dependsOn(cleanIt)
However your compiler complains about type mismatch:

[info] Recompiling project definition...
[info]    Source analysis: 1 new/modified, 0 indirectly invalidated, 0 removed.
[error] C:\Foo\project\build\Project
.scala:14: type mismatch;
[error]  found   : scala.xml.Elem
[error]  required: sbt.ProcessBuilder
How do you solve this?

Answer: add sbt.Process._ to the imports, there is a scala.xml.Elem converter to sbt.ProcessBuilder.

Friday, December 3, 2010

Explicit Self-Types

This is what I think I have learnt about self-types in scala.

Explicit self-typing is one of the various language constructs in Scala for manipulating types. When you use the explicit self-type you don't declare what a type is, like in inheritance, but rather what the type needs to be when concretely used.

Technically when you declare an explicit self-type, you declare what type the "this" reference must obey to.

trait Dependency {

  def first(): Unit;

  def second(): Unit;


trait AConcreteImplementation extends Dependency {

  override def first(): Unit = {
    println("This work was accomplished by AConcreteImplementation :)");

  override def second(): Unit = {
    println("This work was accomplished by AConcreteImplementation too! :) :)");


trait Dependent { self: Dependency => {
    def doSomething(): Unit = {

In this case the trait Dependent must also obey the Dependency interface, it does not matter concretely which kind of real Dependency. Therefore it can use the first() and second() method.

class AnUsableDependent extends Dependent with AConcreteImplementation;

There are three main uses for explicit self-types. The most widest use is about making an assumption on what are the services that will be implemented by actual instances, that is for having type-safe dependency injection using the Cake Pattern.

trait Server {

  def login(): Unit;

  def deleteEverything(): Unit;


trait ServerStub extends Server {

  private def send(server: String, command: String): Unit = {
    println("sending into the wire the command " + command + " to " + server);

  override def login(): Unit = {
    send("", "login");
    println("Logged into the server");

  override def deleteEverything(): Unit = {
    send("", "delete");


trait ClientClass { self: Server => {
    def logInAndDelete(): Unit = {

trait LocalSystem extends Server {

  private def fileSystemDelete(): Unit = {
    println("Asking filesystem to delete files...");

  override def login(): Unit = {
    println("Login not needed: whe are on a local system");

  override def deleteEverything(): Unit = {


Note that this allows you to have different clients, for example:

class RealClient extends ClientClass with ServerStub;

class LocalClient extends ClientClass with LocalSystem;

This use is interesting, since it is most importantly a type safe way of declaring dependency injection. More information and a better example on Cake Pattern on Jonas Boner's blog

A second useful job of explicit self-types is to enforce properties on a current class, expecially when you use it with generics. Let's say you have a generic trait like this:

trait Pluggable[X] {

  def plug(another: X): X;


Without self-types you have no explicit constraint on what can be allowed to represent a Pluggable[X]. The natural choice (in this case Pipe) can be written like this:

class Pipe(var back: Pipe, var front: Pipe) extends Pluggable[Pipe] {

  def this() = {
    this(null, null);

  def plug(another: Pipe): Pipe = {
    this.back = another;
    another.front = this;
    return new Pipe(another, this);


unfortunately anything else could implement this interface too, and we would have no idea on how to stop clients from doing this:

class Socket extends Pluggable[Pipe] {

  def plug(another: Pipe): Pipe = {
    // just for display
    return null;


now, what would happen if we use explicit self-types? We could express the same concept but "strictly"

trait StrictPluggable[X] { self: X => ;

  def plug(another: X): X;


that this would compile:

class StrictPipe(val back: StrictPipe, val front: StrictPipe)
    extends StrictPluggable[StrictPipe] {

  def this() = {
    this(null, null);

  def plug(another: StrictPipe): StrictPipe = {
    return new StrictPipe(new StrictPipe(another, this), new StrictPipe(this, front));


and this, by design, would not:

class Socket extends StrictPluggable[StrictPipe] {

  def plug(another: StrictPipe): StrictPipe = {
    return null;

You can find a better introduction to it on Old Fashioned Software, with a radically better use-case (compare and make mathematical sums on physical dimensions).

There is a third case you might want to use explicit selftypes, and it's the case of enforcing constraints on orthogonality of traits, that is you need to use one (or more) traits only on certain kinds of objects. It's a bit more obscure case than the above, but it's interesting nevertheless: you find an interesting example of it on DZone where the author defines a Tax trait and a Commission trait only on objects that can be traded.

Note that explicit self-types are different from plain inheritance also for two other reasons: first, when you declare

trait B

class A extends B

you are strictly binding A to B. If B was abstract, (and A was not) A would needs to take in itself what would be the concerns of B. the second difference, when you declare

trait Ba {
  def foo();

abstract class Aa { self: Ba => {}

the relationships stays inside Aa, so the following declaration will not compile

class Ca extends Aa;

while these ones will

class C extends A

trait BaImpl extends Ba {
  def foo(): Unit = {

class Ca2 extends Aa with BaImpl

Thursday, November 18, 2010

Can you spot the error? (Type mismatch)

Let's suppose you have this code:

  def eval(input: Int): Unit = {

  def plus[A](a: A*)(implicit numeric: Numeric[A]): A = {
      (a: A, b: A) => numeric.plus(a, b)

  def main(args: Array[String]) {
    eval(plus(1.1, 1));
the compiler will complain with the following error: type mismatch; found : Double(1.1) required: Int. Can you tell why?

It complains because of the eval function requiring an Int parameter.

Saturday, November 13, 2010

SBT, Eclipsify and ScalaTest

Installing SBT and trying to manage an Eclipse project with scala-ide is maybe not the most straightforward thing to do, expecially if you, like me, did not use the command line for a long time, but surely it's saner than installing maven2 and its integration for eclipse :D (sonatype, I am really sorry).

I shied from trying sbt before because of a bad experience with maven, m2 and a private company repository, but I think I will be using sbt for my projects in future. Anyway. The instructions on The SBT setup page are up-to-date and mostly correct. You only have to watch out for the following things:

  • remember either to remove the version-number from the jar file or add the jar version-number in the batch. (Unable to access jarfile C:\correctpath\sbt-launch.jar)
  • The directory where you install the library must not have a space in its path name.
  • If you are behind a proxy, be sure that the password does not contain a reserved character (e.g. !): probably to fix this you can use java -Dhttp.proxyUser=username "-Dhttp.proxyPassword=myPassword^!" ... (note the caret ^, and the quotes "" around the whole -D key/value switch).
  • For NTLM you can always use CNTLM, even if it, in its standard installation version 0.35 (an old version) gives out problems to cygwin for the Administrator user (its cygwin1.dll conflicts with the cygwin installation own dll at least under Vista), no problem with other users
The most beautiful thing about having sbt launched by a .bat file is that in case you are behind ANOTHER proxy, or another network, you can always create a different launcher: e.g.: sbt.bat, sbt-noproxy.bat and sbt-othernetwork.bat (sonatype take note!!!)

Eclipsify and Scalatest again are easy to install. For eclipsify it's just a matter to:

  1. Create the plugin definition under $PROJECT_ROOT/project/plugins for eclipsify
  2. Create the project definition extending the Eclipsify scala trait
  3. give the reload, update and eclipse commands to sbt
If done correct you should have the .classpath and .project files in your $PROJECT_ROOT. For scalatest instead you:
  1. add the scalatest dependency to your project:
    val external_scalatest = "org.scalatest" % "scalatest" % "1.2"
  2. copy the scalatest library from the $HOME/.ivy2/cache/org.scalatest directory to the $PROJECT_ROOT/lib directory
As usual refer to the documentation of Eclipsify and Scalatest. Remember to put the definition of scalatest in your new eclipse project too.

Sunday, October 24, 2010

Problem 02

Again a problem about finding an element in a list, in this case not the last one but the penultimate one.

  // 02 - find the last but one element of a list
  def penultimate[X](of: List[X]): X = {
    of match {
      case Nil => throw new NoSuchElementException
      case a :: Nil => throw new NoSuchElementException
      case _ => return of.tail match {
        case a :: Nil => of.head
        case _ => penultimate(of.tail);

I did not like the use of two matches, one instead the other, but version 2 did not work

  // does not compile
  of match {
    case Nil => throw new IllegalArgumentException
    case head :: Nil => throw new IllegalArgumentException
    case tail :: Nil => of.head; <-- error: unreachable code
//  case of.tail :: Nil => of.head; <-- error: stable identifier required
    case _ => return penultimate(of.tail);

For the fist error, probably the compiler sees

tail :: Nil
as a duplicate of the previous line:
head :: Nil
. Googling the second error reveals that you cannot pattern match against the result of a method invocation. I will investigate more on this.

Looking at the solution however there is a nice surprise, the following expression is valid too:

case head :: _ :: Nil => head
(the "_" character means "any value").

Saturday, October 23, 2010

Problem 01

I am trying to solve Phil Gold's 99 Scala problems (based on Werner Hett's 99 Prolog Problems), so I will post here my solutions and notes. Of course I will not use neither scala (nor java) builtins and I will try to follow the little numbers of things I know about functional programming :)

// 01 - Find the last element of a list.
  def last[X](of: List[X]): X = {
    return of match {
      case a :: Nil => of.head
      case _ => last(of.tail);

This article about pattern matching was useful for seing how too see how lists can be matched using case expressions, in fact an useful general case expression for seeing if a list is not empty is: case head :: tail => println("head (as element): " + head + " tail (as list): " + tail)

The solution posted by Phil underlines that mine does not have a sensible default (he does two matches when he is not at head :: NIL, one for _ :: tail to call the last(tail) method recursively, and one for _ to throw an exception), and that in the first line I could have used the expression case a :: Nil => a to return the head of the list.

Saturday, October 16, 2010

Java varargs in scala

Let's say you want to use a Java api, which has the following stuff: a method which takes a vararg, and a factory utility method in a class with static methods that you should be able to use with the above method.

public void apiMethod(int maxLenght, Stuff... delimiters) {
   // apiMethod does Api stuff

public static Stuff[] sensibleArrayByApi() {
   return new Stuff[] {
      new Stuff(1),
      new Stuff(2)

public void myClientMethod() {
   // something
   apiMethod(256, sensibleArrayByApi());

Now, if you try to translate code of myClientMethod directly to scala (2.8.0.final), you will get an error "overloaded method (types) cannot be applied to (Int,Array[Stuff])". However you can easily solve it by adding the prefix ":_*" to the array

def myClientMethod() : Unit = {
    // apiMethod(256, sensibleArrayByApi) // <--- this will not compile 
    // the following will compile and work
    apiMethod(256, sensibleArrayByApi:_*)

In particular I had this problem while creating a ChannelPipeline object while using Netty, the constructor of DelimiterBasedFrameDecoder and the Delimiters class

result.addLast("framer", new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter: _*))

Thursday, October 14, 2010

Can match expressions be used to wrap batch actions on things?

While writing a method to delete a file, I was thinking that I could use a match expression on an object to check for the object state and eventually manipulate it and return the batch result.

This is a substitution I find elegant to those endless-nested-ifs blocks, but I don't know if there are drawbacks to this approach. I haven't seen any site/doc suggesting it (some OCaml style guides suggest not to use match for substituting simple if expressions, but I don't think this is the case).

package foo

import java.io.File
class FileBatch {

  def delete(asFile: File): String = {
    val result = asFile match {
      case existence if (!asFile.exists) => "File does not exist"
      case writable if (!asFile.canWrite) => "File cannot be deleted"
      case deletable if (!asFile.delete()) => "File was not deleted"
      case ok => "Ok"

object FileBatch {
  def main(args: Array[String]): Unit = {
    // let's get $HOME/.foo/fighter.properties
    val uri = System.getProperty("user.home") + "/.foo/fighter.properties"
    val asFile = new File(uri)

    // and now let's delete it
    val result = new FileBatch().delete(asFile)
    println(new FileBatch().delete(asFile))

Edit: probably the match case, since asFile.delete() actually manipulates the state of the file, could be expressed better by:

    val result = asFile match {
      case existence if (!asFile.exists) => "File does not exist"
      case writable if (!asFile.canWrite) => "File cannot be deleted"
      case _ => {
        val deleted = asFile.delete()
        if (deleted) {
        } else {
          "File was not deleted"

Rate My Scala

Ok, I'm learning how to code in scala, and these are my antics.

object Hello {
  def main(args: Array[String]) {
    println("HI PLANET!");