给定一个类:
class MyClass {
protected object MyObj { ... }
}
是否可以编写一个允许公开MyObj
的特征。例如。继承我可以做到以下几点:
class TestMyClass extends MyClass {
val getMyObj = MyObj
}
但是我想通过一个特性做到这一点,类似下面没有进行类型检查:
trait ExposeMyObj {
val getMyObj = MyObj // super.MyObj/this.MyObj don't work
}
并使用它:
class TestMyClass extends ExposeMyObj
是否可以将TestMyClass
中的功能复制到特征中以暴露受保护对象,如果是,如何?
答案 0 :(得分:1)
如果您知道您的特征将始终混合到MyClass
(或子类)的实例中,您可以使用自我类型强制执行期望,然后访问该对象:
trait ExposeMyObj {
self: MyClass =>
val getMyObj = MyObj
}
修改:使用此特征的示例:
class TestMyClass extends MyClass with ExposeMyObj
val test = new TestMyClass
test.getMyObj // accesses MyObj defined in MyClass.
编辑2 :试图解决@ jbrown的评论(重新:在repos中测试查询) - 我会做类似以下的事情 - 首先,在每个repo的文件中,为每个repo添加一个特征repo持有该回购的查询:
trait UserQueries { // you could look at making this protected, if you like
protected def query1(param: String) = List(param) // very silly implementation, but hopefully enough to make the point
... // other queries
}
class UserRepo extends UserQueries // Has (internal) access to those queries
然后在给定仓库的测试类文件中:
class UserQueriesTester extends UserQueries with ScalaTest { // or whatever test framework you are using
// (public) tests to run - eg:
def testQuery1 = query1("test") should be (List("test"))
}