【问题标题】:correct Scala 3 syntax for providing a given from a higher order function argument正确的 Scala 3 语法,用于从高阶函数参数提供给定
【发布时间】:2022-09-28 10:32:36
【问题描述】:

在 Scala 2 中,我可以这样写:

// a function that needs an implicit context
def funcWithCtx(arg1: String)(implicit ctx: Context) = ???

myObj.doSomething { implicit ctx => // mark argument as the implicit context
  funcWithCtx(\"arg1\")
}

这种语法在 Scala 3 中有效,但我认为 implicit 已被弃用,而 given \\ using 正在被使用?我尝试用given 替换implicit,但编译器不喜欢这样。

myObj.doSomething { given x => // this fails!
  ...
}

这是仍然需要implicit 关键字的地方吗?

  • 耸耸肩新语法更加混乱和混乱。
  • 我又增加了一个选项。

标签: scala implicit scala-3


【解决方案1】:

我猜,正确的是

myObj.doSomething { ctx =>
  given Context = ctx
  ...
}

或者

myObj.doSomething { case ctx@given Context =>
  ...
}

Allow given bindings in patterns

【讨论】:

  • 是的,这就是我最终做的。当新语法为given 时,我不喜欢使用implicit,遗憾的是我们最终添加了一个带有额外样板的新行。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-07-19
  • 1970-01-01
  • 2023-04-05
  • 2016-10-23
  • 2022-01-02
  • 2021-02-01
相关资源
最近更新 更多