为什么我可以将方法标记为隐式,但不能将构造函数标记为隐式?

发布于 2024-11-28 02:12:42 字数 384 浏览 1 评论 0原文

常见的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

亢潮 2024-12-05 02:12:42

如果我正确理解你的问题(请参阅上面的评论),你的想法相当于: 相当于

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

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

如果你想到的不仅仅是脱糖,可能需要对这个问题进行更多思考,以避免构造函数声明的语义过于复杂。

但就小规模语法添加而言,这是建议的,并收到了 Martin 的细致入微但相对积极的评论 Odersky,但我还没有关于实施的消息。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文