This page is no longer maintained — Please continue to the home page at www.scala-lang.org

When is a companion object evaluated?

1 reply
assafzar
Joined: 2009-06-23,
User offline. Last seen 1 year 6 weeks ago.

I copied the "Rational" example from "Programming in Scala" (chapter 6) to Rational.scala.
I defined implicit conversion in the companion object (object Rational { implicit def intToRational(x: Int) = new Rational(x) })

 

I tried to run 2 * r (r is Rational, so implicit conversion is required) from a seperate main function, but it worked only when I wrote the implicit conversion inside the main.
 
My question is, when exactly the companion object code is evaluated? Is there any way to force it?
 
Thanks,
Assaf
 

Tony Sloane
Joined: 2009-01-07,
User offline. Last seen 2 years 32 weeks ago.
Re: When is a companion object evaluated?
Hi Assaf,
On 14/09/2009, at 12:46 AM, Assaf Zaritsky wrote:
I copied the "Rational" example from "Programming in Scala" (chapter 6) to Rational.scala. I defined implicit conversion in the companion object (object Rational { implicit def intToRational(x: Int) = new Rational(x) })   I tried to run 2 * r (r is Rational, so implicit conversion is required) from a seperate main function, but it worked only when I wrote the implicit conversion inside the main.   My question is, when exactly the companion object code is evaluated? Is there any way to force it?

I suspect that your problem is one of scoping, not of evaluation order.  For an implicit to be applicable it must be in scope at the point where it might be used.  Thus if you write 2 * r somewhere and want to use the intToRational implicit there, you need to make sure that intToRational has been imported into to the scope of the 2 * r.  This also explains why it works when you put the implicit into your main function, since that also brings it into scope. In the book the example is being done in the interpreter so the implicit is automatically in scope for later commands.
regards,Tony

Copyright © 2012 École Polytechnique Fédérale de Lausanne (EPFL), Lausanne, Switzerland