Created
July 23, 2010 21:03
-
-
Save stevej/488030 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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()) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Of course, the whole point of no global namespace is that you can avoid details like Array[String] referring to global names.