我正在尝试ZIO。
我不明白为什么Live
添加 as Trait
,然后object
提供 an ,例如:
object Live extends Live
这种模式出现在不同的地方,例如zio.console.Console
。
是否有原因,或者是否存在有意义的情况?
您在ZIO中看到的是一种称为Selfless Trait的模式的使用。
要实现无私特征模式,您只需为本身混合在特征中的特征提供伴随对象。
trait Greeting {
def greet() { println("hi there") }
}
object Greeting extends Greeting
然后库的用户可以选择混合Greeting
:
object MixinExample extends Application with Greeting {
greet()
}
或导入Greeting
伴随对象的成员,如下所示:
import Greeting._
object ImportExample extends Application {
greet()
}
就像对Krzysztof Atłasik回答的补充一样。
正如jq170727评论中提到的,您可以在这里找到这两种情况:
introduction-a-database-module
Object
:
在最坏的情况下,如果我们时间紧迫,需要今天发布代码,也许我们会选择在我们称为邀请朋友的任何地方提供生产数据库。
inviteFriends(userId).provide(DatabaseLive)
在这种情况下,我们可以定义自己的 Runtime,而不是使用 ZIO 附带的 DefaultRuntime,它提供生产数据库模块):
val myRuntime = Runtime(DatabaseLive, PlatformLive)
Trait
:
当您有多个Runtimes时。
val myRuntime =
Runtime(
new DatabaseLive
with SocialLive
with EmailLive, PlatformLive)