scala - 隐式参数的有效用法

标签 scala implicit

以下example来自 A Tour of Scala 展示了如何使用隐式来根据类型提供适当的缺失成员(添加和单元)。编译器将在范围内选择正确的隐式对象。该库还将它与 List.sortBy 一起使用。和 OrderingList.sumNumeric例如。

但是,B 类中的以下用法是隐式参数的有效/推荐用法(与 A 类中不使用隐式参数相反):

class I

class A {
  def foo(i:I) { bar(i) }
  def bar(i:I) { baz(i) }
  def baz(i:I) { println("A baz " + i) }
}
(new A).foo(new I)

class B {
  def foo(implicit i:I) { bar }
  def bar(implicit i:I) { baz }
  def baz(implicit i:I) { println("B baz " + i) }
}
(new B).foo(new I)

在沿堆栈传递参数时,我主要使用隐式在调用站点为自己节省一些输入。

最佳答案

这是一个非常好的用例。当范围确定要使用的参数时,我实际上建议这样做。它提供了一种优雅的方式将某种上下文传递给插件类,以便实用程序函数使用该上下文。例如:

trait Context

object UtilityLib {
  def performHandyFunction(implicit x : Context) : SomeResult = ...
}

trait Plugin {
   def doYourThing(implicit ctx : Context) : Unit
}

class MyPlugin extends Plugin {
  def doYourThing(implicit ctx : Context) : Unit = {
    UtilityLib.performHandyFunction
  }
}

SomePluginAPI.register(new MyPlugin)

您可以在 database migration system I was toying 中查看示例.查看 Migration 类及其 MigrationContext。

关于scala - 隐式参数的有效用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4145370/

相关文章:

performance - Scala递归与循环: performance and runtime considerations

scala 不会警告未使用的计算或值

scala - 猫中的右分离

scala - 为什么Scala 不在这里使用隐式转换?

scala - 来自 super 特征的隐式参数解析

java - 将 java.lang.Boolean 转换为 Scala boolean 值

java - 无法让 log4j 在游戏中运行!框架 2.2.1(scala 项目)

token - 无法为非组合语法中的字符串文字创建隐式标记

scala - Dotty中给出的如何使用?

Scala:泛型和隐式