[英]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
But my Scala
compiler doesn't compile it. 但是我的
Scala
编译器没有编译它。 It says: Cannot resolve reference apply with such signature
. 它说:
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.
只有方法可以有隐式参数。
When you do this: 当你这样做:
// val f: A => Unit =
{
implicit a: A => {
// some action
}
}
you're actually declaring an anonymous function of type A => Unit
and you are declaring the argument a
as implicit in the function body 你实际上是在声明一个类型为
A => Unit
的匿名函数,并且你在函数体中声明了a
隐含的参数a
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()
}
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 你会得到一个弃用警告,因为磁铁必须至少有一个参数而我使用了
Unit
,你应该像.apply(())
一样调用它来避免它
As said by Giovanni: You can't have such a parameter. 正如Giovanni所说:你不能有这样的参数。
However you can use implicitly
to resolve implicits within your function: 但是,您可以
implicitly
使用来解决函数中的含义:
case class Foo(text : String)
implicit val foo = Foo("World")
(() => {
val implFoo : Foo = implicitly[Foo]
println(s"Hello ${implFoo.text}")
}).apply()
(But to be honest this sounds like it can be written better and you're going into spaghetti code territory with what you're doing.) (但说实话,这听起来好像可以写得更好,而且你正在进行意大利面条代码领域与你正在做的事情。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.