我使用Spray并拥有一个Base Route特征,它定义了许多应该实现的功能......
trait ServiceBaseRoute extends HttpService {
def function1():Type
def function2():Type
lazy val serviceBaseRoute = ...
然后我将这个特性混合到许多其他特征......
trait MyRoute1 extends HttpService
with ServiceBaseRoute {
override def function1():Type = {...}
override def function2():Type = {...}
val myRoute1 = serviceBaseRoute
和...
trait MyRoute2 extends HttpService
with ServiceBaseRoute {
override def function1():Type = {...}
override def function2():Type = {...}
val myRoute2 = serviceBaseRoute
最后,我按照以下方式构建路线的顶层......
trait V1Routes extends HttpService
with MyRoute1
with MyRoute2 {
val v1Routes =
pathPrefix("v1") {
authenticate(...) {
myRoute1 ~ myRoute2
}
}
编译精细等...但是当我运行它时,MyRoute2的函数覆盖会覆盖MyRoute1中定义的那些。我想这是因为我没有MyRoute1和MyRoute2的实际实例,因为它们只是混合进来,因为在MyRoute1之后添加了MyRoute2,它的值会覆盖MyRoute1的值? 那么实现这个的最佳方法是保留每个特征中定义的覆盖? 我是否需要将MyRoute1和MyRoute2定义为对象?
由于
答案 0 :(得分:1)
根据您的评论,目标是在MyRoute1和MyRoute2中设置不同的路由,其中每个路由都是通过自定义serviceBaseRoute创建的。由于ServiceBaseRoute是由两个函数自定义的,因此您可以使serviceBaseRoute成为更高阶函数,并将这两个函数的实现传递给子特征:
trait ServiceBaseRoute extends HttpService {
def serviceBaseRoute(f1: () => Type, f2: () => Type)= ???
}
trait MyRoute1 extends HttpService
with ServiceBaseRoute {
def f1ImplA(): Type = ???
def f2ImplA(): Type = ???
val myRoute1 = serviceBaseRoute(f1ImplA, f2ImplA)
}
trait MyRoute2 extends HttpService
with ServiceBaseRoute {
def f1ImplB(): Type = ???
def f2ImplB(): Type = ???
val myRoute2 = serviceBaseRoute(f1ImplB, f2ImplB)
}
trait V1Routes extends HttpService
with MyRoute1
with MyRoute2 {
val v1Routes =
pathPrefix("v1") {
authenticate(...)
{
myRoute1 ~ myRoute2
}
}
}