2

我在类型安全的构建器模式中使用幻像类型来确保方法只被调用一次,如以下代码示例所示

  sealed trait TBoolean
  sealed trait TTrue extends TBoolean
  sealed trait TFalse extends TBoolean

  class Builder[MethodCalled <: TBoolean] private() {

    def foo()(implicit ev: MethodCalled =:= TFalse): Builder[TTrue] = {
      new Builder[TTrue]
    }
  }

  object Builder {
    def apply() = new Builder[TFalse]()
  }

我真的很欣赏这种方法,因为可以使用.-operator 链接方法调用(与其他方法不同)但是,如果有很多方法来保护以类似的结尾,这将变得不方便

  class Builder[MethodCalled1 <: TBoolean, MethodCalled2 <: TBoolean, ... ,MethodCalledN <: TBoolean]

有没有办法创建一个“类型结构”?类似于以下伪代码:

  type S {
      type MethodCalled1 <: TBoolean
      type MethodCalled2 <: TBoolean
      ...
      type MethodCalledN <: TBoolean
  }

  class Builder[S] private() {

    def foo()(implicit ev: S#MethodCalled1 =:= TFalse): Builder[S#MethodCalled1.TTrue] = {
      new Builder[S#MethodCalled1.TTrue]
    }
  }
4

1 回答 1

5

你在正确的轨道上,你只需要添加一点类型改进:

trait BuilderMethods {
  type FooCalled <: TBoolean
  type BarCalled <: TBoolean
}

class Builder[M <: BuilderMethods] private() {
  def foo()(implicit ev: M#FooCalled =:= TFalse): Builder[M {type FooCalled = TTrue}] = {
    new Builder[M {type FooCalled = TTrue}]
  }
  def bar()(implicit ev: M#BarCalled =:= TFalse): Builder[M {type BarCalled = TTrue}] = {
    new Builder[M {type BarCalled = TTrue}]
  }
}

object Builder {
  type UnusedBuilder = BuilderMethods {type FooCalled = TFalse; type BarCalled = TFalse;}
  def apply(): Builder[Builder.UnusedBuilder] = new Builder[UnusedBuilder]()
}

object TestPhantomStruct extends App {
  val newBuilder = Builder()
  val builderFooCalled = newBuilder.foo()
  val builderFooCalledTwice = builderFooCalled.foo() // will not compile
  val builderFooCalledBarCalled = builderFooCalled.bar()
  val builderFooCalledTwiceBarCalled = builderFooCalledBarCalled.foo() // will not compile

  val builderBarCalled = newBuilder.bar()
  val builderBarCalledTwice = builderBarCalled.bar() // will not compile
}
于 2013-01-11T20:14:45.410 回答