Scala OO-可选地扩展性状

时间:2015-03-03 06:48:48

标签: scala

不确定这样的事情是否可行,但我希望实现的效果如下: 我有一个称为物理位置的特征,它需要一个int(对应一个人的城市)作为子类的变量出现。

class Building extends PhysicallySituated //A building has an address
class OilTanker extends Ship //An oiltanker is always moving around
class Yacht extends Ship with Option[ PhysicallySituated ] //a Yacht could have an address

鉴于PhysicallySituated有关于位置操作的方法,我应该如何建模这样的场景?我正在寻找的是在船上调用方法返回一个可选的值,该值是PhysicallySituated中的原始方法将返回的类型。我知道我可以使用PhysicallySituated的实例并调用此实例的方法,但这违背了封装的最佳实践。

我应该注意到我对Scala的理解是中等水平的,但如果有人指出,我愿意阅读任何高级概念

1 个答案:

答案 0 :(得分:3)

这对你有用吗? (随着Scala REPL):

trait Address

case object EmptyAddress extends Address

case class NonEmptyAddress(addrStr: String) extends Address

trait Situated {
  val address: Address
}

trait OptionallySituated extends Situated {
  val address = EmptyAddress
}

trait PhysicallySituated extends Situated {
  val address: NonEmptyAddress
}

class Building extends PhysicallySituated {
  val address = NonEmptyAddress("this is my place")
}

class Ship

class OilTanker extends Ship

class Yacht extends Ship with OptionallySituated

scala> val stuff = List(new Building, new Yacht)
stuff: List[Situated{val address: Product with Serializable with Address}] = List(Building@7e1f584d, Yacht@7dff6d05)

scala> stuff.map(_.address)
res0: List[Product with Serializable with Address] = List(NonEmptyAddress(this is my place), EmptyAddress)                        

您可以将Option[Address]SomeNone一起使用,而不是在上面定义地址类。