Why do people define object extends its companion class?
I find this kind of code is very common in Lift framework, written like this:
object BindHelpers extends BindHelpers {}
What do开发者_StackOverflow中文版es this mean?In this case, BindHelpers
is a trait and not a class. Let foo()
to be a method defined in BindHelpers
, to access it you can either.
Use it through the companion object:
BindHelpers.foo()
Mix the trait
BindHelpers
in a class and thus be able to access the methods inside of it.
For instance:
class MyClass extends MyParentClass with BindHelpers {
val a = foo()
}
The same techniques is used in Scalatest for ShouldMatchers
for instance.
You can find David Pollak's answer to the same question in the liftweb group.
It's interesting for an object
to extend its companion class because it will have the same type as the class.
If object BindHelpers
didn't extend BindHelpers, it would be of type BindHelpers$
.
It might be that the pattern here is other. I don't know Lift to answer this, but there's a problem with object
in that they are not mockable. So, if you define everything in a class
, which can be mocked, and then just makes the object extend it, you can mock the class and use it instead of the object inside your tests.
精彩评论