scala - 如何使隐式可用于内部函数

标签 scala implicit higher-order-functions dotty scala-3

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

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() 可用于内部功能 block ?

最佳答案

这在具有隐式函数类型的 Scala 3 中是可能的(关键字 given 代替 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

关于scala - 如何使隐式可用于内部函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58381138/

相关文章:

scala - 将类型参数的上限交换为证据参数

python - 如何将数据拟合到非理想二极管方程(隐式非线性函数)并检索参数

javascript - 回调也称为高阶函数吗?

java - 使用谓词对字段进行查询

list - 方案高阶函数 - GPA 计算器

scala - 如何在 IntelliJ IDEA 中使用 SBT 构建 Uber JAR(Fat JAR)?

string - Scala:替换字符串中位置 i 处的字符

c# - int 的隐式运算符?

scala - 我应该如何编写带有两个变量的通用函数并将它们添加到 Scala 中?

scala - 如何在 ScalaTest 中按顺序运行类中的测试?