How to make implicits available to inner function

[亡魂溺海] 提交于 2020-12-06 07:07:05

问题


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()
    }
  }
}

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


回答1:


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



来源:https://stackoverflow.com/questions/58381138/how-to-make-implicits-available-to-inner-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!