Skip to content

Instantly share code, notes, and snippets.

@NicolasT
Created August 18, 2009 20:25
Show Gist options
  • Save NicolasT/169926 to your computer and use it in GitHub Desktop.
Save NicolasT/169926 to your computer and use it in GitHub Desktop.
(env-2.6)MacBook:dynamic_scala nicolas $ cat DynamoDemo.scala
// This is a class in some library
class ExternalClass(val a: Int, val b: String)
class InternalClass(val i: Int) {
val j = i * 2
}
object DynamoDemo {
def f(a: ExternalClass) = "" + a.a + " " + a.b
def g(a: InternalClass) = (a.i + a.j) toString
def h(a: {def x: Int; def y: String}) = "" + a.x + " " + a.y
// Yeah yeah, showing off
private def test(fun: => String): Unit = {
println(fun)
}
def main(args: Array[String]): Unit = {
val e = new ExternalClass(10, "Ten")
val i = new InternalClass(20)
// This looks normal
test(f(e))
test(g(i))
// Magic starts here
test(h(new {val x = 30; val y = "thirty"}))
test(f(i))
test(g(e))
test(h(e))
}
implicit def extToInt(o: ExternalClass): InternalClass = {
new InternalClass(o.a)
}
implicit def intToExt(o: InternalClass): ExternalClass = {
new ExternalClass(o.j, o.i toString)
}
implicit def extToFCompatible(o: ExternalClass):
{def x: Int; def y: String} = {
new {val x = o.a; val y = o.b}
}
}
// vim: set ts=4 sw=4 et:
(env-2.6)MacBook:dynamic_scala nicolas $ scalac DynamoDemo.scala
(env-2.6)MacBook:dynamic_scala nicolas $ scala DynamoDemo
10 Ten
60
30 thirty
40 20
30
10 Ten
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment