假设我有这个类和对象层次结构:
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>
}
}
因此,编写器必须在类A
和B
中实现,但不能在对象A中实现,以便此代码可以正常工作。正确的吗?
new A.write
new B.write
因此,必须在对象A中实现writer才能使此代码正常工作。正确的吗?
A.write
答案 0 :(得分:1)
特质:是无国籍的,class
或object
都可以展开trait
。
如果没有任何状态,您可以将其定义为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
如果您希望伴侣对象如下定义,则不必再次扩展特征。
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
在您的示例中,您可以将其定义为trait
,因为我看不到任何状态,您可以将子项定义为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()
}