The Java platform, since Java 6, supports scripting. Mozilla Rhino engine was embedded in JDK 6 and Nashorn is the embedded Javascript engine in recent versions. You can’t, though, write a script in Java language itself. See JSR 292 invokedynamic and this article for more info.
import java.{io, util}
def prettyPrint(f: io.File) = s"${f.getName} ${f.length} ${new util.Date(f.lastModified)}"
val dir = new io.File(args.headOption.getOrElse("."))
dir.listFiles().toStream.map(prettyPrint).foreach(println)
Run the above script as follows:
$ ./ls-scala ..
$ ./ls-scala /home/me/projects
You can run Scala scripts either by Scala script
or by adding #!/usr/bin/env scala
shebang and running ./script
.
Note that the file should have execution permission in this case.
Slow startup time, mostly due to loading classes, makes Scala scripts quite slow.
Use Scala as a script only if it’s a heavy time-consuming task running significantly longer than the startup time. You can also use Scala scripts for casual scripting or when you feel too functional when scripting!
See Ammonite for a typed Scripting API resembling bash.
Groovy is an optionally-typed dynamic JVM-based language fully compatible with Java. It is a general purpose language with scripting support by design.
dir = args ? args[0] : "."
new File(dir).eachFile { println "${it} ${it.size()} ${new Date(it.lastModified())}" }