繁体   English   中英

按名称调用 function 在调用之前进行评估

[英]call-by-name function is evaluated before invoke

我的逻辑是这样的:

def process[T](f1: => T, f2: => T): T = {
  Try { /*Do Something*/ } match {
    case Failure(_) => Try { /*Do something*/ } match {
      case Failure(e) => throw e
      case Success(v1) => 
        // I just need this succeed value be passed to my f1
        // but I dont know how. So...
        implicit val v: V1 = v1
        f1 
    }
    case Success(v2) =>
      // I just need this succeed value be passed to my f1
      // but I dont know how. So...
      implicit val v: V2 = v2
      f2
}

然后我定义f1f2并像这样调用这个process function :

// just for describing this problem clearly
// V1, V2 are two successful output types from the above snippet's branches.
// They are two different types.
// Bar just a dummy Object, Unit will do the same
// I use Bar(v) just to show I processed v in this function.
def f1(implicit v: V1): Bar = Bar(v)
def f2(implicit v: V2): Bar = Bar(v)

process(f1, f2)

然后我收到错误提示No implicit found for f1 有什么帮助吗?

隐式并不像你想象的那样工作。 您必须传递隐式 function 类型而不是按名称参数,但 Dotty 中引入了隐式 function 类型:

// if it was Dotty
def process[T](f1: (given V1) => Bar, f2: (given V2) => Bar) = ...

Scala 2 中没有类似的构造。最接近的近似是带有隐式 arguments 的apply的手写trait

trait F1 { def apply()(implicit v: V1): Bar }
trait F2 { def apply()(implicit v: V2): Bar }

def process[T](f1: F1, f2: F2): T = {
  Try { /*Do Something*/ } match {
    case Failure(_) => Try { /*Do something*/ } match {
      case Failure(e) => throw e
      case Success(v1) =>
        implicit val v: V1 = v1
        f1()
    }
    case Success(v2) =>
      implicit val v: V2 = v2
      f2()
  }
def f1: F1 = new F1 { def apply()(implicit v: V1): Bar = Bar(v) }
def f2: F2 = new F2 { def apply()(implicit v: V2): Bar = Bar(v) }

process(f1, f2)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM