Scala中的伴随对象和类访问

时间:2018-06-05 20:02:17

标签: scala

假设我有这个类和对象层次结构:

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>
   }
}

因此,编写器必须在类AB中实现,但不能在对象A中实现,以便此代码可以正常工作。正确的吗?

new A.write
new B.write

因此,必须在对象A中实现writer才能使此代码正常工作。正确的吗?

A.write

1 个答案:

答案 0 :(得分:1)

特质:是无国籍的,classobject都可以展开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()
}