Sunday, September 18, 2011

Shell like code in Scala...

When you starts a Java Virtual Machine, the current directory is set to the directory in which the JVM was started, and it can't be modified any more. If you want to write some shell-like commands in scala, you'll have to find a way to write you're own change directory command (cd), but as the current directory can't be modified, it is not so simple.

One approach is to use an implicit mutable variable (which will contain the current directory) and change some implicit definitions which came with scala.sys.process.
#!/bin/sh
exec scala "$0" "$@"
!#
import sys.process.Process
import sys.process.ProcessBuilder._

case class CurDir(cwd:java.io.File)
implicit def stringToCurDir(d:String) = CurDir(new java.io.File(d))
implicit def stringToProcess(cmd: String)(implicit curDir:CurDir) = Process(cmd, curDir.cwd)

implicit var cwd:CurDir="/tmp"
def cd(dir:String=util.Properties.userDir) = cwd=dir

// ----------------------
"pwd"!

cd("/var/tmp/")
"pwd"!

cd("/var/log/")
"pwd"!

cd()
"pwd"!



No comments:

Post a Comment