如何将特征声明为采用隐式“构造函数参数"?
我正在设计一个类层次结构,它由一个基类和几个特征组成.基类提供了几种方法的默认实现,并且特征通过abstract override
有选择地覆盖某些方法,以便充当可堆叠的traits/mixins.
I'm designing a class hierarchy, which consists of a base class along with several traits. The base class provides default implementations of several methods, and the traits selectively override certain methods via abstract override
, so as to acts as stackable traits/mixins.
从设计的角度来看,这很好,并且可以映射到域,以便我可以从此处(一个特征)添加谓词,并从此处(另一个特征)添加谓词,等等.
From a design perspective this works well, and maps to the domain so that I can add a filtering function from here (one trait) with a predicate from here (another trait) etc.
但是,现在我希望一些特征可以使用隐式参数.我很高兴从设计角度来看这仍然有意义,并且在实践中不会引起混淆.但是,我无法说服编译器与之一起运行.
However, now I'd like some of my traits to take implicit parameters. I'm happy that this still makes sense from a design perspective, and wouldn't prove confusing in practice. However, I cannot convince the compiler to run with it.
问题的核心似乎是我无法为特征提供构造函数参数,因此可以将其标记为隐式.在方法实现中引用隐式参数无法使用预期的找不到隐式值"消息进行编译;我试图通过构造阶段(实际上在实践中始终在范围内)隐式"传播隐式对象,以通过
The core of the problem seems to be that I cannot provide constructor arguments for a trait, such that they could be marked implicit. Referencing the implicit parameter within a method implementation fails to compile with the expected "could not find implicit value" message; I tried to "propagate" the implicit from construction stage (where, in practice, it's always in scope) to being available within the method via
implicit val e = implicitly[ClassName]
但是(毫无疑问,您中的许多人希望如此) 定义失败,并显示相同的消息.
but (as no doubt many of you expect) that definition failed with the same message.
这里的问题似乎是我无法说服编译器使用implicit ClassName
标志标记特征本身的签名,并迫使调用者(即那些将特征混合到对象中的调用者)提供隐式的.目前,我的调用方 正在这样做,但是编译器未在此级别进行检查.
It seems that the problem here is that I can't convince the compiler to tag the signature of the trait itself with an implicit ClassName
flag, and force callers (i.e. those who mix the trait into an object) to provide the implicit. Currently my callers are doing so, but the compiler isn't checking at this level.
是否有任何方法可以将特征标记为要求在构造时可用某些隐式?
(如果没有,这是否还没有实施?或者有更深层的原因说明这是不切实际的吗?)
(And if not, is this simply not implemented yet or is there a deeper reason why this is impractical?)
实际上,我以前很想这样做,但只是想出了这个主意.您可以翻译
Actually, I've wanted this quite often before, but just came up with this idea. You can translate
trait T(implicit impl: ClassName) {
def foo = ... // using impl here
}
trait T {
// no need to ever use it outside T
protected case class ClassNameW(implicit val wrapped: ClassName)
// normally defined by caller as val implWrap = ClassNameW
protected val implWrap: ClassNameW
// will have to repeat this when you extend T and need access to the implicit
import implWrap.wrapped
def foo = ... // using wrapped here
}