In the Scala programming language, you can turn water into wine, or vice versa, using implicit conversion.
Imagine that you have a class called Weird:
class Weird(s :String) {
def imWeird :String = {
"I'm "+ s +" and I'm weird!"
}
}
It consists of merely a string,
s, and a method, imWeird, that returns a jolly message containing the very same string. (Thus, the codeval freak = new Weird("a freak")outputs
println(freak.imWeird)
I'm a freak and I'm weird!.)Now, Scala allows you to create an implicit conversion that adds the method(s) of
Weird to any other class. Or rather, turns an object into a Weird whenever one calls Weird's methods (functions) on the given object.For example, the following implicit conversion
implicit def string2Weird(s: String) = new Weird(s)makes it possible to call
Weird's method(s) on a String. This codeval happy = "Happy"will now output
println(happy.imWeird)
I'm Happpy and I'm weird!
The name of the implicit conversion method,
string2Weird, is arbitrary.