为什么我可以将方法标记为隐式,但不能将构造函数标记为隐式?
常见的 Enrich-My-Library 模式似乎类似于为什么
class Foo(value: Int)
implicit def int2Foo(i: Int) = new Foo(i)
不能像这样将隐式
添加到构造函数本身,
class Foo implicit (value: Int)
考虑到构造函数只不过是一个方法一些额外的限制?
令人惊讶的是,以下方法确实有效:
class Foo(value: Int) {
implicit def this(a: String) = this(a.toInt)
}
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)
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果我正确理解你的问题(请参阅上面的评论),你的想法相当于: 相当于
:
如果你想到的不仅仅是脱糖,可能需要对这个问题进行更多思考,以避免构造函数声明的语义过于复杂。
但就小规模语法添加而言,这是建议的,并收到了 Martin 的细致入微但相对积极的评论 Odersky,但我还没有关于实施的消息。
If I understand your question correctly (see my comment above) what you are thinking of amounts to this:
Would amount to:
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.