11

I'd like to add implicit conversions to Java classes generated by a modeling tool. So I want to add them to the companion object of those classes, so that the compiler automatically finds them. But I cannot add them in a separate file, because the companion has to be defined in the same file. Is there anything I can do about this?

Of course, I can define all my implicit conversions in another object and then bring it into scope, but this requires an extra import. Any other solution?

Mechanical snail
  • 29,755
  • 14
  • 88
  • 113
Jean-Philippe Pellet
  • 59,296
  • 21
  • 173
  • 234
  • 2
    You could define implicit conversions in the package object, avoiding the extra import. – axel22 Feb 07 '11 at 13:41
  • Java classes don't have a companion object. Do you mean you're trying to cheat and make it look like a Java class has a companion object? – Rex Kerr Feb 07 '11 at 13:48
  • @Rex Kerr: Yeah, well, I didn't know it was considered cheating. @axel22: Good idea, I think I'll go ahead with that! – Jean-Philippe Pellet Feb 07 '11 at 13:56
  • 3
    I actually would like to ask a similar question when the purpose is to write a pattern extractor (`unapply`) for the Java class, without having to use a different name for the object. – Ken Bloom Feb 07 '11 at 14:18

2 Answers2

10

You can define your own companion object of course, which I often do in my own project-specific Predef-like arrangement. For example:

object domain {

  type TimeUnit = java.util.concurrent.TimeUnit
  object TimeUnit {
    def valueOf(s : String) = java.util.concurrent.TimeUnit.valueOf(str)
    val Millis = java.util.concurrent.TimeUnit.MILLISECONDS
    //etc
  }

Then this can be used:

import my.domain._
val tu : TimeUnit = TimeUnit.valueOf("MILLISECONDS")

But your domain.TimeUnit is a module (i.e. scala object)

oxbow_lakes
  • 133,303
  • 56
  • 317
  • 449
9

With the Scala compiler as it stands now there is no way to define companion objects other than by putting them in the same file. The best you can do is a non-companion object with the same package and name and an extra import.

If you can think of a good way to create post-hoc companionship without breaking assumptions about encapsulation please come post on http://groups.google.com/group/scala-debate because it would clearly be a very useful feature.

James Iry
  • 19,367
  • 3
  • 64
  • 56