3

常见的 Enrich-My-Library 模式似乎类似于

class Foo(value: Int)

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

为什么不能implicit像这样将其添加到构造函数本身

class Foo implicit (value: Int)

考虑到构造函数只不过是一个带有一些额外限制的方法?

令人惊讶的是,以下方法确实有效:

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

1 回答 1

5

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

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

相当于:

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

如果它不仅仅是您想到的脱糖,那么可能需要更多地考虑这个问题,以避免过度复杂化构造函数声明的语义。

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.

于 2011-08-05T10:44:37.130 回答