Skip to content

Instantly share code, notes, and snippets.

@stevej
Created July 23, 2010 21:03
Show Gist options
  • Save stevej/488030 to your computer and use it in GitHub Desktop.
Save stevej/488030 to your computer and use it in GitHub Desktop.
/**
* This is an exmaple of how to program in scala without the use of imports or
* global namespaces. Foo seeing Bar's members does not rely on the fact
* that they are in the same package.
*
* Inspired by Gilad Bracha's talk at the Emerging Languages conference in 2010.
*
* Built with scala 2.8.0-final
*/
class Foo(val bar: Bar) {
private class FooFrob extends bar.Frob {
override def apply() = 1
}
class FrobMaker extends bar.FrobMaker {
def apply(): bar.Frob = new FooFrob
}
}
trait Bar {
trait Frob {
def apply() = 0
}
trait FrobMaker {
def apply(): Frob;
}
}
object Main {
def main(args: Array[String]) {
// Passing in an anonymous subclass of the Bar trait.
val foo = new Foo(new Bar{})
// This calls the apply method on Foo.FrobMaker to get a Bar.FrobMaker
// and then calls apply on Bar.FrobMaker to construct a Frob.
val frob = new foo.FrobMaker()()
println("frob() = " + frob())
}
}
@olabini
Copy link

olabini commented Jul 24, 2010

Of course, the whole point of no global namespace is that you can avoid details like Array[String] referring to global names.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment