Friday, May 23, 2014

Tips on using Scala interactive mode

I enjoy interactive scripting tool like irb, but scala doesn't go very friendly as ruby. As I have to specify the class path in order to import my own packages. :/

So, I wrote a shell script automating it. As I always put all jar's in a lib/ folder, this script will get all the .jar files and add them into the classpath:

LIB_PATH=`find lib | tr "\n" :`
scala -cp .:$LIB_PATH

Save this into scala.sh, and run it at the directory where you have the lib/ folder. scala

Unfortunately, Java class names are not as simple and short as ruby. My memory is so bad that I cannot remember the package name of every single class. So, I create this shell script to help myself:

find lib -name \*.jar -exec unzip -v {} \; | grep -oh --color=never '[^[:space:]]*class$' | tr / . | sed -E 's/^(.*).class$/import \1/' > /tmp/imports.scala


Run this from where you lib/ folder is, and it will find all the classes with package names, and store into /tmp/imports.scala. Then in the interactive mode, you can search in this file and copy and paste the import class from a text editor. :D

It is always helpful to script common things in a text editor, such as initialize hbase connection, etc. Load them into scala by typing in the terminal so that we are not doing the boring thing again:
:load hbase_init_script.scala

The snippets are here on Gist:
https://gist.github.com/yuhanz/02155cfa921d6ef17014
https://gist.github.com/yuhanz/8002c696fbac9dd35ff2

No comments: