pme*_*pme 2 singleton scala traits zio
我正在尝试ZIO。
我不明白为什么Live将添加为Trait,然后object提供,例如:
object Live extends Live
Run Code Online (Sandbox Code Playgroud)
例如,可以在不同的地方找到此模式zio.console.Console。
是否有原因,或者在某些情况下有意义?
您在ZIO中看到的是使用一种称为“ 无私特质 ”的模式。
要实现无私特征模式,您只需为本身混合在特征中的特征提供一个伴随对象。
trait Greeting {
def greet() { println("hi there") }
}
object Greeting extends Greeting
Run Code Online (Sandbox Code Playgroud)
然后,库的用户可以选择混入Greeting:
object MixinExample extends Application with Greeting {
greet()
}
Run Code Online (Sandbox Code Playgroud)
或导入Greeting伴随对象的成员,如下所示:
import Greeting._
object ImportExample extends Application {
greet()
}
Run Code Online (Sandbox Code Playgroud)