[英]Companion objects and class access in Scala
Say I have this class and object hierarchy: 说我有这个类和对象层次结构:
class A extends BB
class B extends BB
object A extends BB
abstract class BB {
def writer: Writer (<say Writer is a custom class>)
def write: {
writer.<dothing>
}
}
So writer has to be implemented in class A
and B
but not object A right in order for this code to work. 因此,编写者必须在类
A
和B
实现,但不能在对象A上实现,才能使此代码起作用。 Correct? 正确?
new A.write
new B.write
So writer has to be implemented in object A in order for this code to work. 因此必须在对象A中实现writer才能使此代码起作用。 Correct?
正确?
A.write
trait : is stateless, and class
or object
both can extend trait
. 特质 :是无状态的,
class
或object
都可以扩展trait
。
You define something as object
when it does not have any states. 当没有任何状态时,可以将某物定义为
object
。
scala> trait CanFly {
| def fly: String
| }
defined trait CanFly
scala> class DuckCanFly extends CanFly {
| override def fly: String = "duck duck"
| }
defined class DuckCanFly
scala> object EagleCanFly extends CanFly {
| override def fly: String = "eagle eagle"
| }
defined object EagleCanFly
scala> new DuckCanFly().fly
res0: String = duck duck
scala> EagleCanFly.fly
res1: String = eagle eagle
If you want companion object define it as below, you don't have to extend the trait again. 如果您希望伴随对象定义如下,则无需再次扩展特征。
scala> :paste
// Entering paste mode (ctrl-D to finish)
class DuckCanFly extends CanFly {
override def fly: String = "duck duck"
}
object DuckCanFly {
def apply(): DuckCanFly = new DuckCanFly()
}
// Exiting paste mode, now interpreting.
defined class DuckCanFly
defined object DuckCanFly
scala> DuckCanFly().fly
res8: String = duck duck
In your example, you can define it as trait
as I do not see any state, and you can define childs as object
. 在您的示例中,您可以将其定义为
trait
因为我看不到任何状态,并且可以将childs定义为object
。
trait BB {
def writer: Writer
def write = writer.write()
}
object A extends BB {
def writer: Writer = new AWriter()
}
object B extends BB {
def writer: Writer = new BWriter()
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.