Scala:如何使用隐式参数定义匿名函数? [英] Scala: How to define anonymous function with implicit parameter?
问题描述
我想用这样的方式定义一个带有隐式参数的函数:
I want to define a function with implicit parameter in a way like this:
// imports to add scope of A
{
implicit a: A => {
// some action
}
}.apply()
// somewhere in the code
class A
val a: A = new A
但是我的Scala
编译器没有编译它.它说:Cannot resolve reference apply with such signature
.但是,该参数是隐式的,因此我认为编译器应在范围内查找并找到合适的对象.
But my Scala
compiler doesn't compile it. It says: Cannot resolve reference apply with such signature
. However, the parameter is implicit, so I guess compiler should look up in the scope and find an appropriate object.
是真的吗?如果没有,我该如何解决?
Is it true? If not, then how can I fix it?
推荐答案
您不能.只有方法可以具有隐式参数.
You can't. Only methods can have implicit parameters.
执行此操作时:
// val f: A => Unit =
{
implicit a: A => {
// some action
}
}
您实际上是在声明一个类型为A => Unit
的匿名函数,并且您将参数a
声明为函数主体中的隐式
you're actually declaring an anonymous function of type A => Unit
and you are declaring the argument a
as implicit in the function body
您可以使用磁铁图案实现接近所需的效果:
You can achieve something close to what you want using the magnet pattern:
class A
case class Magnet()
object Magnet {
implicit def fromUnit(arg1: Unit)(implicit a: A) = Magnet()
}
object Test extends App {
implicit val a = new A
{
args: Magnet => {
//...
}
}.apply()
}
尽管磁铁必须至少具有一个参数并且我使用了Unit
,但您仍会收到弃用警告,因此应使用.apply(())
来称呼它以避免它
You'll get a deprecation warning though because the magnet must have at least one parameter and I used Unit
, you should call it like .apply(())
to avoid it
这篇关于Scala:如何使用隐式参数定义匿名函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!