gpt4 book ai didi

scala - 隐式参数的有效用法

转载 作者:行者123 更新时间:2023-12-05 00:39:51 25 4
gpt4 key购买 nike

以下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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com