我想以这样的方式定义一个带有隐式参数的函数:
// 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
.但是,参数是隐式的,所以我猜编译器应该在范围内查找并找到合适的对象。这是真的吗?如果没有,那么我该如何解决?
最佳答案
你不能。只有方法可以有隐式参数。
当你这样做时:
// val f: A => Unit =
{
implicit a: A => {
// some action
}
}
你实际上是在声明一个
A => Unit
类型的匿名函数并且您正在声明参数 a
隐含在函数体中您可以使用磁铁图案实现接近您想要的效果:
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(())
避免它
关于Scala:如何使用隐式参数定义匿名函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36809817/