部分应用具有隐式参数的函数 [英] Partially applying a function that has an implicit parameter

查看:70
本文介绍了部分应用具有隐式参数的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以将采用隐式参数的方法转换为函数吗?

Can I turn a method which takes an implicit parameter into a function?

trait Tx

def foo(bar: Any)(implicit tx: Tx) {}

foo _ // error: could not find implicit value for parameter tx: Tx

我正在尝试实现以下目标,最好是如果我能以某种方式使其与普通调用withSelection(deleteObjects)一起工作:

I am trying to achieve the following, preferably if I can somehow make it work with the plain call withSelection(deleteObjects):

trait Test {      
  def atomic[A](fun: Tx => A): A

  def selection: Iterable[Any]

  def withSelection(fun: Iterable[Any] => Tx => Unit) {
    val sel = selection
    if (sel.nonEmpty) atomic { implicit tx =>
      fun(sel)(tx)
    }
  }

  object deleteAction {
    def apply() {
      withSelection(deleteObjects)  // !
    }
  }

  def deleteObjects(xs: Iterable[Any])(implicit tx: Tx): Unit
}


我发现了这个问题,但是它不涉及方法的取消据我所知,功能正常.


I found this question, however it does not deal with the lifting from methods to functions as far as I can see.

推荐答案

隐式仅对方法有效.但是您必须将一个函数传递给withSelection.您可以通过将方法包装在函数中来解决这个问题:

Implicits only work for methods. But you have to pass a function to withSelection. You can get around by wrapping the method in a function:

withSelection(a => b => deleteObjects(a)(b))

不可能直接通过deleteObjects,因为foo _不适用于定义了隐式参数列表的foo.

Its impossible to pass deleteObjects directly because foo _ does not work for a foo with an implicit parameter list defined.

这篇关于部分应用具有隐式参数的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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