Thursday, 12 September 2013

Implicit conversion paradox

Implicit conversion paradox

If I try to define an implicit conversion for a primitive type, then it
doesn't seem to work. E.g.:
implicit def globalIntToString(a: Int) : String = { a.toString() +
"globalhi" }
1.toInt + "hi"
The above will still return simply "1hi" as the result.
However, it seems that if I parameterize a class or a def and then pass in
the implicit for the parametrized case, then it seems to work. Does anyone
know what the reasons are? E.g. does this have something to do with
boxing/unboxing of primtives (e.g., parameterized primitives are boxed)?
Does implicit only work with reference types and not primitive types?
class typeConv[T] { implicit def tToStr(a: T) : String = { a.toString() +
"hi" } }
class t[K](a: K)(tc : typeConv[K]) { import tc._; println(a + "cool");
println(1.toInt + "cool" ) }
new t(1)(new typeConv[Int])

No comments:

Post a Comment