3

The common Enrich-My-Library pattern seems to be something like

class Foo(value: Int)

implicit def int2Foo(i: Int) = new Foo(i)

Why isn't it possible to just add the implicit to the constructor itself like this

class Foo implicit (value: Int)

considering that the constructor isn't much more than a method with some additional restriction?

Surprisingly, the following does work:

class Foo(value: Int) {
  implicit def this(a: String) = this(a.toInt)
}
0__
  • 66,707
  • 21
  • 171
  • 266
soc
  • 27,983
  • 20
  • 111
  • 215
  • Isn't it [Pimp My Library](http://www.artima.com/weblogs/viewpost.jsp?thread=179766) you mean ? If so, there's a [tag for that](http://stackoverflow.com/questions/tagged/pimp-my-library). – Francois G Aug 05 '11 at 10:07
  • FYI: https://issues.scala-lang.org/browse/SI-4882 – gerferra Aug 06 '11 at 14:49

1 Answers1

5

If I understand your question correctly (see my comment above) what you are thinking of amounts to this:

implicit class Foo(val i : Int) {
 ...
}

Would amount to:

implicit def int2Foo(x : Int) = new Foo(x)
class Foo(val i : Int) {
 ...
}

If it's more than desugaring you have in mind, there probably is some more thought to be given to the problem to avoid over-complexifying the semantics of the constructor declaration.

But as far as the small-scale syntax addition goes, this has been suggested, and has received nuanced but relatively positive comments from Martin Odersky, but I have no news on implementation yet.

Francois G
  • 11,957
  • 54
  • 59
  • No, not really ... why would we need desugaring here? My ideas was simply allowing to add `implicit` to the constructor. Adding `implicit` to a class? No idea what the semantics should be ... – soc Aug 05 '11 at 10:52
  • 1
    In that case, what would "allowing to add implicit to the constructor" mean, else than the desugaring I suggest above ? – Francois G Aug 05 '11 at 11:04
  • I just don't see the point of your desugaring suggestion. It doesn't work like that currently, why should it be added for some "special case"? – soc Aug 05 '11 at 11:53
  • Just for reference, this syntax change has been accepted: http://docs.scala-lang.org/sips/pending/implicit-classes.html – Blaisorblade Apr 11 '12 at 23:20