Archive for the 'scala' Category

03
Sep
11

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.

Advertisements
03
Sep
11

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)
Wor
ord
rdp
dpr
pre
res
ess

03
Sep
11

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")

03
Sep
11

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.


import tools.nsc.io._

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

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:


import tools.nsc.io._

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("STDOUT:")
println(stdOut.mkString("
"))
println("END OF STDOUT:")

println("STDERR:")
println(stdErr.mkString("\n"))
println("END OF STDERR")

println(dirProc.exitValue)
dirProc.destroy

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:


Some(1)

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? 🙂

02
Feb
10

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="Manifest.mf">
			<zipfileset src="scala-library.jar" /> 
			<fileset dir=".">
				<include name="*.class" /> 
			</fileset>
		</jarjar>
	</target>
 </project>

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.

31
Jan
10

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:


import java.io._

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 Manifest.mf 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(ClassLoader.java:632)
        at java.lang.ClassLoader.defineClass(ClassLoader.java:616)
        at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:14
1)
        at java.net.URLClassLoader.defineClass(URLClassLoader.java:283)
        at java.net.URLClassLoader.access$000(URLClassLoader.java:58)
        at java.net.URLClassLoader$1.run(URLClassLoader.java:197)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
        at Whatever.main(x.scala)
Caused by: java.lang.ClassNotFoundException: scala.ScalaObject
        at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
        ... 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.

25
Jun
09

scala syntax


I’m not very fond of the scala syntax.




Blog Stats

  • 225,275 hits