Archive for the 'scala' Category


notepad++ & scala

If you want to have the syntax highlighted by Notepad++, copy the file userDefineLang.xml, from your Scala installation’s miscscala-tool-supportnotepad-plus to the Notepad++ directory, in the Application Data folder. If you don’t know where this folder is, open a command prompt, and write:

echo %APPDATA%

Be sure to restart Notepad++, and choose the Scala entry in the syntax menu.


scala sliding

Here’s a cool little utility Scala provides. The sliding method, which allows you access to consecutive pairs of elements. Here’s an example of how it’s used:

scala> "Wordpress".sliding(3).foreach(println)


scala catching exceptions

Here’s a way to deal with possible exceptions in Scala. Let’s say your application takes command line arguments, and it will work with either 2 or 3 arguments. The thing is, if you have 2 and you try to acces the 3rd, you’ll get an ArrayIndexOutOfBoundsException. Of course, you could check the size before accessing. But, let’s just see another way:

import scala.util.control.Exception._

val firstArgument     = args(0)
val secondArgument = args(1)
val thirdArgument     = catching(classOf[ArrayIndexOutOfBoundsException]).opt(args(2)).getOrElse("default value")


scala process output

At one point or another, we all want to execute an external process from our scripts, capture it’s output in a variable, and do something with it. In typical scripting languages, this operation is very painless. Take Ruby, for example:

dir_output = `cmd.exe /c dir`

This would execute the dir command, and store it's output in the dir_output variable. dir_output's class is String.

As it turns out, it's not very difficult to achieve the same thing in Scala.


val dirOutput = Process("cmd.exe /c dir").stdout.collect { case line:String => line }

In this case, we're executing the same dir command, and we're iterating over the standard output, collecting the results. The type of the dirOutput is going to be Iterable[String], which allows for all that iterator goodness we're all used to.

Even though in most cases, this is enough to get your work done, it's good practice to check for a process's exit code, and it's standard error stream. Take the following example:


val dirProc = Process("camd.exe /c dir")
val stdOut  = dirProc.stdout.collect { case line:String => line }
val stdErr  = dirProc.stderr.collect { case line:String => line }

println("END OF STDOUT:")

println("END OF STDERR")


As you can notice, I have a typo in the above snippet. I am executing camd.exe instead of cmd.exe, and unless you magically have a binary named camd.exe which accepts a /c flag, the process would most likely exit with an error code different than 0.

To access the process's exit code, we use the exitValue method. Because this method returns an Option[Int], you'd see this as output:


Here's how you'd find out the actual code of the process:

println(dirProc.exitValue match {
	case Some(value) => value match {
		case 0 => "success"
		case _ => "failure"
	case _ => "thread exception?"

Any code different than 0 means failure. If the exitValue returns None, it probably means that an exception occured, probably an IllegalThreadStateException, as documented in the JDK doc.

I'd say working with a process in Scala is quite pleasant. Wouldn't you? 🙂


creating an executable jar out of your Scala code

In the previous post about creating an executable jar from your Scala code, I showed how to create the jar using your favourite compression software.
Today, you’ll see how to do it using jarjar. jarjar can be used to package all of your jars into a single one, thus eliminating external dependencies.
The great part is that it has an ant task, so I’ll show you how to use that:

<project name="jarjar tester">
	<target name="jrjr">
		<taskdef name="jarjar" classname="com.tonicsystems.jarjar.JarJarTask" classpath="jarjar-1.0.jar" /> 
		<jarjar destfile="jrjarilo.jar" manifest="">
			<zipfileset src="scala-library.jar" /> 
			<fileset dir=".">
				<include name="*.class" /> 

You need to supply it with a manifest, so, you could use the one from here. You need to adjust the paths to your scala-library.jar and to jarjar.jar, and to specify the name you’d like your jar to receive.

If everything goes well ( and it should ), after running this target you should have your own executable jar, containing the Scala runtime.


the not so elegant way of creating an executable jar from scala code

For a while now I kept thinking how I would create an executable jar that would contain the Scala runtime. Tonight, I decided to give it a shot and try to make it work.
If you don’t already know, a jar is nothing but a zip file that includes a manifest ( which holds some information ).
To test this, I used the following code:


object Whatever
	def main(args:Array[String]) = {
		new File(args(0)).listFiles.foreach(println)

So … first we compile it to bytecode. We use scalac for that:

scalac x.scala

If you’re using the code I posted above, you should get 3 classes out of the compilation process. Next, we need to create a manifest:

Main-Class: Whatever

Please notice there is an extra line after the line with Main-Class.

Now, we need to actually create the jar. We use the jar binary that ships with your Java installation:

jar -cvfm h.jar Whatever.class Whatever$$anonfun$main$1.class Whatever.class Whatever$.class

Ok, so if we now run the existing h.jar jar, you should get this exception:

Exception in thread "main" java.lang.NoClassDefFoundError: scala/ScalaObject
        at java.lang.ClassLoader.defineClass1(Native Method)
        at java.lang.ClassLoader.defineClassCond(
        at java.lang.ClassLoader.defineClass(
        at Method)
        at java.lang.ClassLoader.loadClass(
        at sun.misc.Launcher$AppClassLoader.loadClass(
        at java.lang.ClassLoader.loadClass(
        at Whatever.main(x.scala)
Caused by: java.lang.ClassNotFoundException: scala.ScalaObject
        at Method)
        at java.lang.ClassLoader.loadClass(
        at sun.misc.Launcher$AppClassLoader.loadClass(
        at java.lang.ClassLoader.loadClass(
        ... 13 more

It’s because it can’t find the Scala runtime. So … here comes the “not so elegant way” of adding the Scala runtime 🙂 . In your Scala’s installation folder, you have a folder named lib which contains a jar named scala-library.jar. I’m assuming you have some software that can extract zip archives ( I think most operating systems have this by default ). Extract that archive to some directory, and notice the scala folder. Now, open the jar we created above using your favourite compression software. You should have the following structure:

Remember the scala package I told you about a couple of lines above? Simply drag it into your archive, at the same level as the META-INF folder, like in the following picture:

After this is over, you can try to run your jar again:

java -jar h.jar .

And it should/will work. In a day or two, I’ll show you how to accomplish the same thing using jarjar.


scala syntax

I’m not very fond of the scala syntax.

Blog Stats

  • 262,482 hits