This is my Blog.

It's full of opinions on a wide range of stuff.

Calling AppleScript from Scala

It occoured to me today that it would be a doddle to control parts of OSX from the Scala REPL. Check this out below, the script itself simply says "Hello World" out loud but it would be easy to substitute in something more meaningful.

scala> import javax.script._
import javax.script._

scala> val script = "say \"Hello World\"" 
script: java.lang.String = say "Hello World" 

scala> val mgr = new ScriptEngineManager
mgr: javax.script.ScriptEngineManager = 
  javax.script.ScriptEngineManager@8094cc7

scala> val engine = mgr.getEngineByName("AppleScript")
engine: javax.script.ScriptEngine = 
  apple.applescript.AppleScriptEngine@16cc8a48

scala> val context = engine.getContext                
context: javax.script.ScriptContext =
   javax.script.SimpleScriptContext@2278e185

scala> val bindings = context.getBindings(ScriptContext.ENGINE_SCOPE)
bindings: javax.script.Bindings = 
  javax.script.SimpleBindings@65712a80

scala> engine.eval(script, context)
res0: java.lang.Object = null

That's all there is too it. Scalatastic!

blog comments powered by Disqus