Created
March 10, 2012 15:48
-
-
Save eyston/2011848 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
// scala | |
// adding interfaces to classes | |
trait Greetable { | |
def Greeting: String | |
} | |
def greet(g: Greetable): Unit = { | |
println(g.Greeting) | |
} | |
class GreetableString(s: String) extends Greetable { | |
def Greeting: String = { | |
"Hello " + s | |
} | |
} | |
implicit def stringToGreetable(s: String): GreetableString = new GreetableString(s) | |
val foo: String = "Fred" | |
// can now use Greeting like a C# extension method | |
foo.Greeting // # String = "Hello Fred" | |
// but can also pass string to things that require Greetable | |
greet(foo) // # prints "Hello Fred" | |
// so we've extended String with the trait Greetable, which you can't do with c# extension methods | |
// | |
// it isn't magic, it just ends up doing something like: | |
// | |
// greet(new GreetableString(foo)) | |
// | |
// which is exactly what you would have to do in c#. | |
// it is just one way that implicits are a more general thing than extension methods | |
// (I also don't fully grok them) | |
// another example -- passing implicit parameters to stuff | |
def greetMany(n: Int)(implicit g: Greetable): Unit = { | |
for(i <- 0 until n) { println(g.Greeting) } | |
} | |
implicit val misterGreetable: Greetable = foo | |
greetMany(3) | |
// # prints Hello Fred | |
// # prints Hello Fred | |
// # prints Hello Fred | |
// so this gets transformed into | |
// | |
// greetMany(3)(misterGreetable) | |
// | |
// this is the kinda stuff that seems very sharp :) | |
// | |
// I think the common pitfal is if you import multiple namespaces defining the same implicit val it can be a pain to debug |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment