开发者

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

开发者 https://www.devze.com 2023-03-25 21:26 出处:网络
The common Enrich-My-Library pattern seems to be something like class Foo(value: Int) implicit def int2Foo(i: Int) = new Foo(i)

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 mo开发者_开发百科re than a method with some additional restriction?

Surprisingly, the following does work:

class Foo(value: Int) {
  implicit def this(a: String) = this(a.toInt)
}


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消