2

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

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()提供给内部功能块?

4

1 回答 1

6

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

于 2019-10-14T17:46:03.350 回答