I write
object MyString {
implicit def stringToMyString(s: String) = new MyString(s)
}
class MyString(str: String) {
def camelize = str.split("_").map(_.capitalize).mkString
override def toString = str
}
object Parse {
def main(args: Array[String]) {
val x = "active_record".camelize
// ...
}
}
in my program. This causes a compiling error. After I inserted
import MyString.stringToMyString
Then it works.
From Odersky’s Programming in Scala I got that implicit conversion in the companion object of the source or expected target types don’t need to be imported.
True enough. Now, the method
camelizeis defined on the classMyString, and, indeed, there is an implicit conversion toMyStringinside its object companion. However, there is nothing in the code telling the compiler thatMyStringis the expected target type.If, instead, you wrote this:
then it would work, because the compiler would know you expect
"active_record"to be aMyString, making it look up the implicit conversion inside objectMyString.This might look a bit restrictive, but it actually works in a number of places. Say, for instance, you had:
And then you had a code like this:
Now,
xdoes have a+method, whose expected type isFraction. So the compiler would look, here, for an implicit conversion fromInttoFractioninside the objectFraction(and inside the objectInt, if there was one, since that’s the source type).