Importing symbols in Gypsum

Published on 2015-10-28
Tagged: gypsum

View All Posts

The import statement is one of several new language features I added to Gypsum this summer. Just like the import statement in Java, it makes definitions from another package available in the scope containing the import statement. Unlike Java, multiple definitions can be imported in the same statement. Definitions can also be renamed.

Here are a few examples:

// Import the class `Option` from the `std` package.
import std.Option

// Import multiple definitions from `std`.
import std.Option, Some, None

// Import and rename multiple definitions.
import std.Option as Maybe, Some as Just, None as Nothing

// Import all definitions from `std`.
import std._

Import statements can be used in any scope; they don't have to appear at the top of the file. You could use them in a function or class for example. Imported symbols are lexically scoped.

def f =
  import std.Some
  Some[String]("foo")

You can even import static methods from classes. Eventually, I'd like to be able to import non-static methods and fields, but this requires associating some context (the receiver) with imported symbols, so it's a little more complicated.

class Box[static T](value: T)
  static def create(value: T) = Box[T](value)

import Box[String].create as create-string-box
let box = create-string-box("foo")

When you use a definition from another package (whether the definition is imported or it's accessed by its fully qualified name), the package is automatically added to the dependency list of the package being compiled. No extra flags are needed on the compiler's command line. Only definitions with the public attribute may be imported from other packages.

As always, Gypsum is open source, and you can find it at GitHub.