Scala:如何使用隐式参数定义匿名函数? [英] Scala: How to define anonymous function with implicit parameter?

查看:129
本文介绍了Scala:如何使用隐式参数定义匿名函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用这样的方式定义一个带有隐式参数的函数:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆