Search code examples
classscalaconstructorimplicitenrich-my-library

Why can I mark methods as implicit but not the constructor?


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)
}

Solution

  • 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.