soc*_*soc 3 constructor scala class implicit enrich-my-library
常见的Enrich-My-Library模式似乎是这样的
class Foo(value: Int)
implicit def int2Foo(i: Int) = new Foo(i)
Run Code Online (Sandbox Code Playgroud)
为什么不能implicit像这样只添加到构造函数本身
class Foo implicit (value: Int)
Run Code Online (Sandbox Code Playgroud)
考虑到构造函数不仅仅是一个带有一些额外限制的方法?
令人惊讶的是,以下确实有效:
class Foo(value: Int) {
implicit def this(a: String) = this(a.toInt)
}
Run Code Online (Sandbox Code Playgroud)
如果我正确地理解了您的问题(请参阅上面的评论),您对此的想法是多少:
implicit class Foo(val i : Int) {
...
}
Run Code Online (Sandbox Code Playgroud)
相当于:
implicit def int2Foo(x : Int) = new Foo(x)
class Foo(val i : Int) {
...
}
Run Code Online (Sandbox Code Playgroud)
如果你想到的不仅仅是贬低,那么可能会更多地考虑问题,以避免过度复杂化构造函数声明的语义.
但是就小规模的语法添加而言,这已被提出,并且已经收到 Martin Odersky的细微但相对积极的评论,但我还没有关于实现的消息.