有可能做以下的事情吗?
def takeCurriedFnAsArg(f: (Int)(implicit MyClass) => Result)发布于 2013-10-26 17:49:58
是的,这是可能的。
当您将第二个咖喱参数标记为implicit时,该函数似乎是而不是类型的
Int => (MyClass => Result) => ResultOfFunction 如果curried的高阶函数参数是一个规则参数,那么它将是这样的;相反,它看起来如下:
Int => ResultOfFunction下面是一个简单的例子:
scala> def curriedFn(i : Int)(implicit func : String => Int) : Boolean = (i + func("test!")) % 2 == 0
curriedFn: (i: Int)(implicit func: String => Int)Boolean
scala> implicit val fn : String => Int = s => s.length
fn: String => Int = <function1>
scala> curriedFn _
res4: Int => Boolean = <function1>如您所见,implicit参数被“删除”了。为什么和怎么做?这是一个比我更有见识的人的问题。如果我不得不猜测,我会说编译器直接用隐式值替换参数,但这很可能是错误的。
总之,撇开消化,这里有一个与你的情况非常相关的例子:
scala> def foo(func : Int => Boolean) = if(func(3)) "True!" else "False!"
foo: (func: Int => Boolean)String
scala> foo(curriedFn)
res2: String = True!现在,如果第二个函数参数不是隐式的:
scala> def curriedNonImplicit(i : Int)(fn : String => Int) : Boolean = (i + fn("test!")) % 2 == 0
curriedNonImplicit: (i: Int)(fn: String => Int)Boolean
scala> curriedNonImplicit _
res5: Int => ((String => Int) => Boolean) = <function1>如您所见,函数的类型有点不同。这意味着解决方案看起来也会有所不同:
scala> def baz(func : Int => (String => Int) => Boolean) = if(func(3)(s => s.length)) "True!" else "False!"
baz: (func: Int => ((String => Int) => Boolean))String
scala> baz(curriedNonImplicit)
res6: String = True!您必须在方法中直接指定函数,因为它以前没有隐式提供。
https://stackoverflow.com/questions/19609444
复制相似问题