开发者

Why do people define object extends its companion class?

开发者 https://www.devze.com 2023-02-10 21:23 出处:网络
I find this kind of code is very common in Lift framework, written like this: object BindHelpers extends BindHelpers {}

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.

  1. Use it through the companion object: BindHelpers.foo()

  2. 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消