扩展具有需要隐式成员的特征的对象 [英] Extending an object with a trait which needs implicit member
问题描述
我正在尝试使用如下代码:
I'm trying to have a code like below:
object MetaData extends CacheParams{}
因此,由于 CacheParams
需要隐式val p:Parameters
,我尝试了:
So, since CacheParams
needs implicit val p:Parameters
, I tried:
对象元数据(隐式val p:参数)扩展了CacheParams
但是似乎我无法将参数传递给对象.
But it seems that I can't pass arguments to an object.
(因为它会给出错误:特征或对象可能没有参数
)
( because it gives error:traits or objects may not have parameters
)
如果我不传递任何参数,则会出现以下编译错误:
And if I don't pass any arguments it will give compile error that:
[error]: object creation impossible, since value p in trait CacheParams of type Parameters is not defined
我不知道该如何运作.有一些类似的问题,但是他们的答案都不能解决我的问题.任何帮助将非常感激.非常感谢.
I have no idea how to make this works. There were a few similar questions, but none of their answers solved my problem. Any help would be really appreciated. Thanks a lot.
推荐答案
如果我猜对了 CacheParams
的定义
trait Parameters
trait CacheParams {
implicit val p: Parameters
}
然后您应该:(1)替换对象
then you should: (1) replace the object
object MetaData /*(implicit val p: Parameters)*/ extends CacheParams
//object creation impossible. Missing implementation for:
// implicit val p: Parameters // inherited from trait CacheParams
上课
class MetaData(implicit val p: Parameters) extends CacheParams
或(2)在对象内部实现隐式
or (2) implement the implicit inside the object
object MetaData extends CacheParams {
override implicit val p: Parameters = new Parameters {}
}
或
implicit val params: Parameters = new Parameters {} // suppose an implicit is in current scope
object MetaData extends CacheParams {
override implicit val p: Parameters = {
val p = ??? // hiding above p to avoid ambiguous implicits, null or NPE, see (*) below
implicitly[Parameters]
}
}
(*)隐式分辨率上的NullPointerException
在(1)中,您正在当前作用域中定义/解析隐式.在(2)中,将隐式解析推迟到实例化类之前(在类构造函数调用站点的范围内解析隐式).
In (1) you're defining/resolving implicit now in current scope. In (2) you postpone resolving implicit till instantiating the class (resolving implicit in the scope of class constructor call site).
另请参见通过乘法对象传递隐式参数
是的,这可以解决我的问题.但是我想保持对象的主体清洁,并使其与Parameters中的配置分离,例如接受
p:Parameters
的类的主体.
如果在(1)中,您要使对象与" Parameters
中的配置"解耦,您可以尝试引入特征( ParamsMaterializer
):
If in (1) you want to decouple the object from "the configuration in Parameters
" you can try to introduce a trait (ParamsMaterializer
):
object MetaData extends CacheParams with ParamsMaterializer
trait ParamsMaterializer {
implicit val p: Parameters = new Parameters {}
}
或
implicit val params: Parameters = new Parameters {} // suppose an implicit is in current scope
object MetaData extends CacheParams with ParamsMaterializer
trait ParamsMaterializer {
implicit val p: Parameters = {
val p = ???
implicitly[Parameters]
}
}
这篇关于扩展具有需要隐式成员的特征的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!