This is a study note for Ammonite. The reason is to use the Ammonite as my Scala REPL to code snipptes during my reading of the book: Programming In Scala, 4th Edition.

1 Introduction

Ammonite is a mondern Scala REPL that has syntax highlighting, multi-line editing, library importing and other desired features missing in the default Scala REPL. It is lightweight without the project setting and loading of sbt. Additionally, it comes with a filesystem library that make possbile to use it as a system shell.

The Ammonite-REPL supports the following features

  • pretty printing using PPrint
  • editing with syntax highlighting, multi-liine editing, key-binding, history search, block input
  • importing scripts and Ivy dependencies
  • session saving and loading
  • auto completion
  • interrupting with Ctrl-C
  • configuratble with ~/.ammonite/

Scala script let you save and run code without settings of a project. A script can import other scripts. Scripts may take arguments.

2 Basic REPL

  • Run Ammonite: amm
  • Exit: exit or Ctrl-D
  • Interrupt current execution: Ctrl-C
  • Consel key-bindings
    • delete a word: Ctrl-W
    • moving cursor
    • start of the line: Ctrl+A or Home
    • end of the line: Ctrl+E or End
    • one word left/right: Esc-B/F or Opt-Left/Right
    • clear the screen: Ctrl-L
    • Stop/Resume screen output: Ctrl-S/Q
    • Undo: Ctrl-_
    • Redo: Opt/Esc-_
  • Auto completion: use tab
  • Save/load sessions
    • repl.sess.load()

3 Script Files

Import a file using import $file.MyScript, without the .sc postfix. To import script a file and its objects, using import $file.MyScript, MyScript._. To import and dump definitions, use import $exec.MyScript.

To import a library, use the following

import $ivy.`org::library:version`, org.library._

Use amm -w to watch the file and rerun it when there is a change in the script. Use amm -w -p to watch and open an REPL.

4 Ops

Ammonite-Ops is a library that provides common filesytem operations in Scala. The operations are:

  • ls! path and ls.iter! path: return Vector[Path] or Iterator[Path]
  • ls.rec! path and ls.rec.iter! path: run recursively
  • read! path, read.lines! path, read.bytes! path
  • write(path, content)
  • rm! path: rm -rf
  • mv(src, dest)
  • cp(src, dest): cp -r src dest
  • exists! path
  • stat! path

It provides the following extensions:

  • things | f: things map f
  • things || f: things flatMap f
  • things |? f: things filter f
  • things |& f: things reduce f
  • things |! f: things foreach f
  • thing |> f or f! thing: f(thing)

To spawning subprocess, use %cmd to run shell command. It requires import ammonite.ops.ImplicitWd._.

To take command line parameters, use the follwoing definition:

def main(p1: T1, p2, T2) =  { ... }

// or arguments
def main(args: String*) = { ... }