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

问题描述 投票:2回答:1

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

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

scala implicit higher-order-functions dotty
1个回答
4
投票

在具有隐式函数类型的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

© www.soinside.com 2019 - 2024. All rights reserved.