如何使用适当的 apply 方法将对象隐式转换为函数?
正如问题所说,我正在尝试以下操作(无法编译):
object O {
def apply(i: Int): Boolean = i % 2 == 0
}
val f: Int => Boolean = O
所以我尝试了这个:
implicit def apply2Fct[A,B](applier: { def apply(a: A): B }) = {
new Function[A,B] { def apply(a: A): B = applier(a) }
}
但是编译器抱怨“结构细化中的参数类型可能不会引用该细化之外定义的抽象类型” 。
编辑:
由于Jean-Philippe Pellet的回答,我不得不提到我不能让O
扩展Function[A ,B]
分别是函数[Int,Boolean]
。
As the question says I am trying the following (does not compile):
object O {
def apply(i: Int): Boolean = i % 2 == 0
}
val f: Int => Boolean = O
So I tried this:
implicit def apply2Fct[A,B](applier: { def apply(a: A): B }) = {
new Function[A,B] { def apply(a: A): B = applier(a) }
}
But the compiler complains about "Parameter type in structural refinement may not refer to an abstract type defined outside that refinement".
EDIT :
Due to the answer of Jean-Philippe Pellet I have to mention that I can´t let O
extend Function[A,B]
respectively Function[Int,Boolean]
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您不能直接执行此操作,原因是 Gilles 在 ticket #967 上给出的原因。有问题的构造是在结构类型内的方法定义的裸参数位置中出现外部定义的类型参数 A。
然而,我们可以通过消除有问题的情况来近似期望的结果,转而使用内部类型参数,并加上类型约束,迫使它在应用该方法的任何点都等于原始参数类型 A。
为此,您必须修改您尝试从结构上捕获的方法的签名的一般形式(注意:伪代码如下),
以
针对您的特定情况,我们需要如下所示的
示例 REPL 会话,
You can't do this directly for the reasons that Gilles gives on ticket #967. The problematic construct is the occurrence of the externally defined type parameter A in a bare argument position on a method definition within the structural type.
However, we can approximate the desired result by eliminating the problematic occurrence in favour of an internal type parameter coupled with a type constraint forcing it to be equal to the original argument type A at any point at which the method is applied.
To do this you have to modify the general form of the signatures of the methods you're trying to capture structurally from (nb. pseudocode follows),
to
For your particular case we would need something like the following,
Sample REPL session,
如果您没有考虑过并且代码实际上在您手中,您也可以简单地这样做:
或者,将结构类型显式地放入 f,可以说:
In case you haven’t thought about it and the code is actually in your hands, you might also simply do:
Or, putting the structural type explicitly to f, one could say:
您应该明确告诉编译器
O
是一个函数:You should explicitly tell the compiler that
O
is a function:您是否尝试过将隐式转换设为非参数化(我意识到这不是很好)?
Have you tried making the implicit conversion non-parameterized (not great, I realize)?