如何使隐式函数可用于内部函数 [英] How to make implicits available to inner function

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

问题描述

我想在包装器函数中定义隐式值,并将其提供给内部函数使用,到目前为止,我设法通过从包装器传递隐式变量来做到这一点:

I would like to define implicit value in a wrapper function and make it available to inner function, so far I managed to do that by passing implicit variable from wrapper:

case class B()

trait Helper {
  def withImplicit[A]()(block: => A): A = {
    implicit val b: B = B()
    block
  }
}

class Test extends Helper {
  def useImplicit()(implicit b: B): Unit = {...}

  def test = {
    withImplicit() { implicit b: B =>
      useImplicit()
    }
  }
}

是否可以避免implicit b: B =>并使implicit val b: B = B()可用于内部功能块?

Is it possible to avoid implicit b: B => and make implicit val b: B = B() available to inner function block?

推荐答案

在具有隐式函数类型的Scala 3中(关键字given代替implicit),这是可能的

This will be possible in Scala 3 with implicit function types (keyword given is instead of implicit)

case class B()

trait Helper {
  def withImplicit[A]()(block: (given B) => A): A = {
    given B = B()
    block
  }
}

class Test extends Helper {
  def useImplicit()(given b: B): Unit = {}

  def test = {
    withImplicit() {
      useImplicit()
    }
  }
}

https://dotty.epfl.ch/docs/reference/contextual/implicit-function-types.html

https://dotty.epfl.ch/blog/2016/12/05/implicit-function-types.html

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

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