常见的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)
}发布于 2011-08-05 18:44:37
如果我正确理解了你的问题(参见我上面的评论),你的想法是这样的:
implicit class Foo(val i : Int) {
...
}将相当于:
implicit def int2Foo(x : Int) = new Foo(x)
class Foo(val i : Int) {
...
}如果你考虑的不仅仅是去丑化,那就使用there probably is some more thought to be given to the problem来避免构造函数声明的语义过于复杂。
但就小规模的语法添加而言,这是suggested,并且有来自Martin Odersky的received nuanced but relatively positive comments,但我还没有关于实现的消息。
https://stackoverflow.com/questions/6953975
复制相似问题