【发布时间】:2016-10-20 05:14:18
【问题描述】:
我想为具有私有构造函数的类添加一个隐式参数。这里作为一个简化的例子:
class A[T] private(a:Int){
def this()=this(0)
}
如果我想使用 Ordered[T] 将 Pimp my library 模式应用到 T,我需要使用(已弃用的)视图绑定,如下所示:
class A[T <% Ordered[T]] private(a:Int){
def this()=this(0)
}
这很有效。但是,为了避免不推荐使用的语法糖,我想将隐式参数传递给类。不幸的是,这可能是我做错了什么:
class A[T] private(a:Int)(implicit conv:T=>Ordered[T]){
def this()=this(0)
}
对于上述代码,编译器会产生如下错误:
error: No implicit view available from T => Ordered[T].
def this()=this(0)
如果我尝试像这样直接传递隐式参数:
class A[T] private(a:Int)(implicit conv:T=>Ordered[T]){
def this()=this(0)(conv)
}
我明白了:
error: not found: value conv
def this()=this(0)(conv)
在这种情况下如何传递隐式参数?
编辑:经过更多实验后,似乎用隐式参数重新定义构造函数是问题所在。不是构造函数是私有的事实。
【问题讨论】:
标签: scala constructor implicits