实现支持方法链的Scala特征的最佳实践

时间:2011-01-28 08:52:07

标签: scala method-chaining traits

我想创建一个特性,为类添加一些属性,并使链式方法成为可能。在Scala 2.8.1中测试。

trait SomeProperty {
    var prop : String = "default"
    def setProp(s: String) = {
        prop = s
        this
    }
}
sealed abstract class Value
case class IntegerValue(v: Int) extends Value
case class FloatValue(v: Float) extends Value with SomeProperty {
    def foo() = { println("I'm foo.") }
}
case object UnknownValue extends Value with SomeProperty {
    def bar() = { println("I'm bar.") }
}

scala> val x = UnknownValue
scala> x.setProp("test").bar()
<console>:10: error: value bar is not a member of SomeProperty
   x.setProp("test").bar()

在这种情况下最常见的做法是什么? (首选类型安全的方式)

3 个答案:

答案 0 :(得分:20)

您可以显式指定实例类型作为setProp的返回类型。

trait SomeProperty {
    var prop : String = "default"
    def setProp(s: String):this.type = {
        prop = s
        this
    }
}

答案 1 :(得分:1)

不确定这是否是您正在寻找的

scala> trait Property[T] {
     |   me: T =>
     |   var prop:String=""
     |   def setProp(s:String) = {
     |     prop=s
     |     me
     |   }
     | }
defined trait Property

scala> class A extends Property[A]
defined class A

scala> class B extends Property[B]
defined class B

scala> val a= new A
a: A = A@694a18

scala> val b = new B
b: B = B@1108691

scala> a.setProp("Hi")
res13: Property[A] with A = A@694a18

scala> a.setProp("Hi").setProp("Bye")
res14: Property[A] with A = A@694a18

scala> b.setProp("D")
res15: Property[B] with B = B@1108691

答案 2 :(得分:0)

最简单的方法是使用通用。

object Value {

  trait SomeProperty[X] {
    var str: String = null;
    def setStr(s: String): X = {
      str = s;
      return this.asInstanceOf[X]
    }
  }

  abstract sealed class Value
  case class IntegerValue(i: Int)
  case class StringValue(s: String) extends SomeProperty[StringValue] {
    def foo(): Unit = {
      println("Foo.")
    }
  }
  case class UnknownValue(o: Any) extends SomeProperty[UnknownValue] {
    def bar(): Unit = {
      println("Bar.")
    }
  }

  def main(args: Array[String]): Unit = {

    new UnknownValue(18).setStr("blah blah blah").bar
    new StringValue("A").setStr("halb halb halb").foo
  }
}
相关问题